merge main
This commit is contained in:
commit
aa71c9f483
235 changed files with 6234 additions and 4286 deletions
4
.changes/unreleased/Added-20241129-164631.yaml
Normal file
4
.changes/unreleased/Added-20241129-164631.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: Tool use
|
||||
time: 2024-11-29T16:46:31.677532-08:00
|
||||
4
.changes/unreleased/Added-20241129-164644.yaml
Normal file
4
.changes/unreleased/Added-20241129-164644.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: Support for Model Context Protocol
|
||||
time: 2024-11-29T16:46:44.960691-08:00
|
||||
|
|
@ -4,4 +4,5 @@ docs/docs/languages
|
|||
.idea/
|
||||
.vscode/
|
||||
.archive/
|
||||
**/*.scm
|
||||
**/*.scm
|
||||
**/*.diff
|
||||
4
binary/package-lock.json
generated
4
binary/package-lock.json
generated
|
|
@ -49,6 +49,7 @@
|
|||
"@aws-sdk/credential-providers": "^3.620.1",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/llm-info": "^1.0.2",
|
||||
"@modelcontextprotocol/sdk": "^1.0.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.0.2",
|
||||
"@typescript-eslint/eslint-plugin": "^7.8.0",
|
||||
|
|
@ -59,7 +60,7 @@
|
|||
"cheerio": "^1.0.0-rc.12",
|
||||
"commander": "^12.0.0",
|
||||
"comment-json": "^4.2.3",
|
||||
"dbinfoz": "^0.11.0",
|
||||
"dbinfoz": "^0.14.0",
|
||||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
|
|
@ -82,6 +83,7 @@
|
|||
"onnxruntime-node": "1.14.0",
|
||||
"openai": "^4.20.1",
|
||||
"p-limit": "^6.1.0",
|
||||
"partial-json": "^0.1.7",
|
||||
"pg": "^8.11.3",
|
||||
"posthog-node": "^3.6.3",
|
||||
"puppeteer": "^22.4.0",
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { TRIAL_FIM_MODEL } from "../config/onboarding.js";
|
|||
import { IDE, ILLM } from "../index.js";
|
||||
import OpenAI from "../llm/llms/OpenAI.js";
|
||||
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
|
||||
import { EXPERIMENTS, PosthogFeatureFlag, Telemetry } from "../util/posthog.js";
|
||||
|
||||
import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js";
|
||||
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
|
||||
|
|
@ -66,7 +67,11 @@ export class CompletionProvider {
|
|||
|
||||
// Set temperature (but don't override)
|
||||
if (llm.completionOptions.temperature === undefined) {
|
||||
llm.completionOptions.temperature = 0.01;
|
||||
const value = await Telemetry.getValueForFeatureFlag(
|
||||
PosthogFeatureFlag.AutocompleteTemperature,
|
||||
);
|
||||
|
||||
llm.completionOptions.temperature = value ?? 0.01;
|
||||
}
|
||||
|
||||
if (llm instanceof OpenAI) {
|
||||
|
|
|
|||
|
|
@ -10,13 +10,13 @@ import {
|
|||
IGNORE_PATH_PATTERNS,
|
||||
LanguageName,
|
||||
} from "../../../util/treeSitter";
|
||||
import { AstPath } from "../../util/ast";
|
||||
import { ImportDefinitionsService } from "../ImportDefinitionsService";
|
||||
import { AutocompleteSnippetDeprecated } from "../../types";
|
||||
import {
|
||||
AutocompleteCodeSnippet,
|
||||
AutocompleteSnippetType,
|
||||
} from "../../snippets/types";
|
||||
import { AutocompleteSnippetDeprecated } from "../../types";
|
||||
import { AstPath } from "../../util/ast";
|
||||
import { ImportDefinitionsService } from "../ImportDefinitionsService";
|
||||
|
||||
function getSyntaxTreeString(
|
||||
node: Parser.SyntaxNode,
|
||||
|
|
@ -112,7 +112,6 @@ export class RootPathContextService {
|
|||
);
|
||||
snippets.push(...newSnippets);
|
||||
} catch (e) {
|
||||
debugger;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { stopAtStartOf, stopAtStopTokens } from "./charStream";
|
|||
import {
|
||||
avoidEmptyComments,
|
||||
avoidPathLine,
|
||||
noDoubleNewlineAfterClosingBracket,
|
||||
noDoubleNewLine,
|
||||
showWhateverWeHaveAtXMs,
|
||||
skipPrefixes,
|
||||
stopAtLines,
|
||||
|
|
@ -49,7 +49,7 @@ export class StreamTransformPipeline {
|
|||
);
|
||||
lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment);
|
||||
lineGenerator = skipPrefixes(lineGenerator);
|
||||
lineGenerator = noDoubleNewlineAfterClosingBracket(lineGenerator);
|
||||
lineGenerator = noDoubleNewLine(lineGenerator);
|
||||
|
||||
for (const lineFilter of helper.lang.lineFilters ?? []) {
|
||||
lineGenerator = lineFilter({ lines: lineGenerator, fullStop });
|
||||
|
|
|
|||
|
|
@ -171,46 +171,45 @@ describe("stopAtStartOf", () => {
|
|||
controlPlaneEnv.CONTROL_PLANE_URL,
|
||||
),
|
||||
`;
|
||||
|
||||
/* Some LLMs, such as Codestral, repeat the suffix of the query. To test our filtering, we cut the sample code at random positions, remove a part of the input
|
||||
and construct a response, containing the removed part and the suffix. The goal of the stopAtStartOf() method is to detect the start of the suffix in the response */
|
||||
it("should stop if the start of the suffix is reached", async () => {
|
||||
const removeLength = 10;
|
||||
for (let i = 0; i < sampleCode.length - removeLength - 20; i++) {
|
||||
const removed = sampleCode.slice(i, i + removeLength);
|
||||
const suffix = sampleCode.slice(i + removeLength);
|
||||
const response = removed + suffix;
|
||||
const suffix = `
|
||||
const data = await response.json();
|
||||
return data.items;
|
||||
}`;
|
||||
const mockStream = createMockStream(sampleCode.split(/(?! )/g));
|
||||
const result = stopAtStartOf(mockStream, suffix);
|
||||
|
||||
// split the response but keep spaces
|
||||
const mockStream = createMockStream(response.split(/(?! )/g));
|
||||
const result = stopAtStartOf(mockStream, suffix);
|
||||
|
||||
const resultStr = await streamToString(result);
|
||||
if (resultStr !== removed) {
|
||||
throw new Error(
|
||||
`i=${i} result:\n${resultStr}\n\nremoved:\n${removed}\n\nsuffix:\n${suffix}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const resultStr = await streamToString(result);
|
||||
expect(resultStr).toBe(` {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: \`Bearer \${this.workOsAccessToken}\`,
|
||||
},
|
||||
},
|
||||
);
|
||||
`);
|
||||
});
|
||||
it("should stop if the start of the suffix is reached, even if the suffix has a prefix", async () => {
|
||||
const removeLength = 10;
|
||||
for (let i = 0; i < sampleCode.length - removeLength - 20; i++) {
|
||||
const removed = sampleCode.slice(i, i + removeLength);
|
||||
let suffix = sampleCode.slice(i + removeLength);
|
||||
const response = removed + suffix;
|
||||
// add a prefix to the suffix
|
||||
suffix = "strange words;\n which start the suffix#" + suffix;
|
||||
const suffix = `
|
||||
xxxconst data = await response.json();
|
||||
return data.items;
|
||||
}`;
|
||||
const mockStream = createMockStream(sampleCode.split(/(?! )/g));
|
||||
const result = stopAtStartOf(mockStream, suffix);
|
||||
|
||||
// split the response but keep spaces
|
||||
const mockStream = createMockStream(response.split(/(?! )/g));
|
||||
const result = stopAtStartOf(mockStream, suffix);
|
||||
|
||||
const resultStr = await streamToString(result);
|
||||
if (resultStr !== removed) {
|
||||
throw new Error(
|
||||
`i=${i} result:\n${resultStr}\n\nremoved:\n${removed}\n\nsuffix:\n${suffix}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const resultStr = await streamToString(result);
|
||||
expect(resultStr).toBe(` {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: \`Bearer \${this.workOsAccessToken}\`,
|
||||
},
|
||||
},
|
||||
);
|
||||
`);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -119,8 +119,9 @@ export async function* stopAtStopTokens(
|
|||
}
|
||||
|
||||
/**
|
||||
* Asynchronously yields characters from the input stream, stopping if a sequence contained in the beginning of the suffix is encountered.
|
||||
* */
|
||||
* Asynchronously yields characters from the input stream.
|
||||
* Stops if the beginning of the suffix is detected in the stream.
|
||||
*/
|
||||
export async function* stopAtStartOf(
|
||||
stream: AsyncGenerator<string>,
|
||||
suffix: string,
|
||||
|
|
@ -132,42 +133,31 @@ export async function* stopAtStartOf(
|
|||
}
|
||||
return;
|
||||
}
|
||||
// We use sequenceLength * 1.5 as a heuristic to make sure we don't miss the sequence if the
|
||||
// stream is not perfectly aligned with the sequence (small whitespace differences etc).
|
||||
const targetPart = suffix
|
||||
.trimStart()
|
||||
.slice(0, Math.floor(sequenceLength * 1.5));
|
||||
|
||||
const n = Math.min(suffix.length, 3 * sequenceLength);
|
||||
let prev = new Array(n + 1).fill(0);
|
||||
let res = 0;
|
||||
let buffer = "";
|
||||
|
||||
for await (const chunk of stream) {
|
||||
const s1 = chunk;
|
||||
const m = chunk.length;
|
||||
for (let i = 1; i <= m; i++) {
|
||||
// Create a temporary array to store the current row
|
||||
let curr = new Array(n + 1).fill(0);
|
||||
for (let j = 1; j <= n; j++) {
|
||||
if (s1[i - 1] === suffix[j - 1]) {
|
||||
curr[j] = prev[j - 1] + 1;
|
||||
res = Math.max(res, curr[j]);
|
||||
} else {
|
||||
curr[j] = 0;
|
||||
}
|
||||
}
|
||||
buffer += chunk;
|
||||
|
||||
// Move the current row's data to the previous row
|
||||
prev = curr;
|
||||
// Check if the targetPart contains contains the buffer at any point
|
||||
if (buffer.length >= sequenceLength && targetPart.includes(buffer)) {
|
||||
return; // Stop processing when the sequence is found
|
||||
}
|
||||
|
||||
if (res > sequenceLength) {
|
||||
return;
|
||||
}
|
||||
|
||||
buffer += s1[i - 1];
|
||||
|
||||
while (buffer.length > sequenceLength) {
|
||||
yield buffer[0];
|
||||
buffer = buffer.slice(1);
|
||||
}
|
||||
// Yield chunk by chunk, ensuring not to exceed sequenceLength in the buffer
|
||||
while (buffer.length > sequenceLength) {
|
||||
yield buffer[0];
|
||||
buffer = buffer.slice(1);
|
||||
}
|
||||
}
|
||||
|
||||
yield buffer;
|
||||
// Yield the remaining buffer if it is not contained in the `targetPart`
|
||||
if (buffer.length > 0) {
|
||||
yield buffer;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -537,53 +537,32 @@ export async function* showWhateverWeHaveAtXMs(
|
|||
ms: number,
|
||||
): LineStream {
|
||||
const startTime = Date.now();
|
||||
let firstNonWhitespaceLineYielded = false;
|
||||
|
||||
for await (const line of lines) {
|
||||
// Always get at least one line
|
||||
yield line;
|
||||
|
||||
// But after that, soft break at X ms
|
||||
if (Date.now() - startTime > ms) {
|
||||
if (!firstNonWhitespaceLineYielded && line.trim() !== "") {
|
||||
firstNonWhitespaceLineYielded = true;
|
||||
}
|
||||
|
||||
const isTakingTooLong = Date.now() - startTime > ms;
|
||||
if (isTakingTooLong && firstNonWhitespaceLineYielded) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function* noDoubleNewlineAfterClosingBracket(
|
||||
lines: LineStream,
|
||||
): LineStream {
|
||||
const bracketTypeCounts = new Map<string, number>();
|
||||
export async function* noDoubleNewLine(lines: LineStream): LineStream {
|
||||
let isFirstLine = true;
|
||||
|
||||
for await (const line of lines) {
|
||||
if (line.trim() === "") {
|
||||
// Double newline detected
|
||||
// Check if any bracket counts are negative
|
||||
let hasNegativeCount = false;
|
||||
for (const count of bracketTypeCounts.values()) {
|
||||
if (count < 0) {
|
||||
hasNegativeCount = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (hasNegativeCount) {
|
||||
// Stop the generator if we've closed brackets we didn't open
|
||||
return;
|
||||
}
|
||||
if (line.trim() === "" && !isFirstLine) {
|
||||
return;
|
||||
}
|
||||
|
||||
isFirstLine = false;
|
||||
|
||||
yield line;
|
||||
|
||||
// Update bracket counts
|
||||
for (const char of line) {
|
||||
if (BRACKETS[char]) {
|
||||
// It's an opening bracket
|
||||
const count = bracketTypeCounts.get(char) || 0;
|
||||
bracketTypeCounts.set(char, count + 1);
|
||||
} else if (BRACKETS_REVERSE[char]) {
|
||||
// It's a closing bracket
|
||||
const openingBracket = BRACKETS_REVERSE[char];
|
||||
const count = bracketTypeCounts.get(openingBracket) || 0;
|
||||
bracketTypeCounts.set(openingBracket, count - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -110,6 +110,7 @@ Here is a list of features:
|
|||
- Feature 2`,
|
||||
},
|
||||
{
|
||||
// options: { only: true },
|
||||
description: "Should autocomplete a Java method within a class",
|
||||
filename: "Calculator.java",
|
||||
input: `
|
||||
|
|
@ -150,37 +151,7 @@ public class Calculator {
|
|||
POSTGRES_DB: mydb
|
||||
`,
|
||||
expectedCompletion: `
|
||||
POSTGRES_DB: mydb
|
||||
`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should filter out suffix generated by LLM (sample from Codestral)",
|
||||
filename: "test.js",
|
||||
input: `
|
||||
add(number) {
|
||||
this.result += number;
|
||||
return this;
|
||||
}
|
||||
// Add the subtract method
|
||||
subtract(number) {<|fim|>
|
||||
|
||||
subtract(number) {
|
||||
this.result -= number;
|
||||
return this;
|
||||
}
|
||||
|
||||
multiply(number) {
|
||||
this.result *= number;
|
||||
return this;
|
||||
}`,
|
||||
llmOutput: ` this.result -= number;
|
||||
return this;
|
||||
}
|
||||
// Add the multiply method
|
||||
multiply(number) {
|
||||
`,
|
||||
expectedCompletion: undefined,
|
||||
POSTGRES_DB: mydb`,
|
||||
},
|
||||
{
|
||||
description: "Should enforce bracket matching in JSON files",
|
||||
|
|
@ -283,8 +254,7 @@ async getContextForPath(
|
|||
): Promise<AutocompleteCodeSnippet[]> {
|
||||
const snippets: AutocompleteCodeSnippet[] = [];
|
||||
`,
|
||||
expectedCompletion: `console.log('TEST');
|
||||
`,
|
||||
expectedCompletion: `console.log('TEST');`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete React effect hook",
|
||||
|
|
@ -333,6 +303,82 @@ export const Timer = () => {
|
|||
llmOutput: ` this;`,
|
||||
expectedCompletion: `this;`,
|
||||
},
|
||||
{
|
||||
description: "Should complete YAML list item and preserve structure",
|
||||
filename: "test.yaml",
|
||||
input: `
|
||||
services:
|
||||
- name: web
|
||||
image: nginx
|
||||
- name: app<|fim|>
|
||||
volumes:
|
||||
- volume1
|
||||
- volume2
|
||||
`,
|
||||
llmOutput: `
|
||||
image: node
|
||||
`,
|
||||
expectedCompletion: `
|
||||
image: node`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should complete YAML key-value pair inside a nested structure",
|
||||
filename: "test.yaml",
|
||||
input: `
|
||||
version: '3'
|
||||
services:
|
||||
db:
|
||||
image: postgres
|
||||
environment:
|
||||
POSTGRES_USER: user
|
||||
POSTGRES_PASSWORD: pass
|
||||
POSTGRES_DB: mydb<|fim|>
|
||||
`,
|
||||
llmOutput: `
|
||||
PGDATA: /var/lib/postgresql/data/pgdata
|
||||
`,
|
||||
expectedCompletion: `
|
||||
PGDATA: /var/lib/postgresql/data/pgdata`,
|
||||
},
|
||||
{
|
||||
description: "Should complete YAML block within an existing block",
|
||||
filename: "test.yaml",
|
||||
input: `
|
||||
pipelines:
|
||||
branches:
|
||||
master:
|
||||
- step:
|
||||
name: Build and Test
|
||||
script:
|
||||
- npm install
|
||||
- npm run test
|
||||
- step:
|
||||
name: Deploy<|fim|>
|
||||
`,
|
||||
llmOutput: `
|
||||
script:
|
||||
- npm run deploy
|
||||
`,
|
||||
expectedCompletion: `
|
||||
script:
|
||||
- npm run deploy`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete SQL query with subquery and alias in SELECT clause",
|
||||
filename: "complex_query.sql",
|
||||
input: `SELECT u.id,
|
||||
u.name,
|
||||
(SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count
|
||||
FROM users u
|
||||
WHERE u.active = 1
|
||||
<|fim|>`,
|
||||
llmOutput:
|
||||
" AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
|
||||
expectedCompletion:
|
||||
"AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
|
||||
},
|
||||
];
|
||||
|
||||
export const TEST_CASES_WITHOUT_DIFF: AutocompleteFileringTestInput[] = [
|
||||
|
|
@ -832,21 +878,6 @@ func main() {
|
|||
llmOutput: " DEFAULT",
|
||||
expectedCompletion: " DEFAULT",
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete SQL query with subquery and alias in SELECT clause",
|
||||
filename: "complex_query.sql",
|
||||
input: `SELECT u.id,
|
||||
u.name,
|
||||
(SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count
|
||||
FROM users u
|
||||
WHERE u.active = 1
|
||||
<|fim|>`,
|
||||
llmOutput:
|
||||
" AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
|
||||
expectedCompletion:
|
||||
" AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete multi-line SQL query with CASE statements",
|
||||
|
|
@ -1030,70 +1061,6 @@ Smart<|fim|>`,
|
|||
llmOutput: "ob, 2023-02-10",
|
||||
expectedCompletion: "ob, 2023-02-10",
|
||||
},
|
||||
{
|
||||
description: "Should complete YAML list item and preserve structure",
|
||||
filename: "test.yaml",
|
||||
input: `
|
||||
services:
|
||||
- name: web
|
||||
image: nginx
|
||||
- name: app<|fim|>
|
||||
volumes:
|
||||
- volume1
|
||||
- volume2
|
||||
`,
|
||||
llmOutput: `
|
||||
image: node
|
||||
`,
|
||||
expectedCompletion: `
|
||||
image: node
|
||||
`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should complete YAML key-value pair inside a nested structure",
|
||||
filename: "test.yaml",
|
||||
input: `
|
||||
version: '3'
|
||||
services:
|
||||
db:
|
||||
image: postgres
|
||||
environment:
|
||||
POSTGRES_USER: user
|
||||
POSTGRES_PASSWORD: pass
|
||||
POSTGRES_DB: mydb<|fim|>
|
||||
`,
|
||||
llmOutput: `
|
||||
PGDATA: /var/lib/postgresql/data/pgdata
|
||||
`,
|
||||
expectedCompletion: `
|
||||
PGDATA: /var/lib/postgresql/data/pgdata
|
||||
`,
|
||||
},
|
||||
{
|
||||
description: "Should complete YAML block within an existing block",
|
||||
filename: "test.yaml",
|
||||
input: `
|
||||
pipelines:
|
||||
branches:
|
||||
master:
|
||||
- step:
|
||||
name: Build and Test
|
||||
script:
|
||||
- npm install
|
||||
- npm run test
|
||||
- step:
|
||||
name: Deploy<|fim|>
|
||||
`,
|
||||
llmOutput: `
|
||||
script:
|
||||
- npm run deploy
|
||||
`,
|
||||
expectedCompletion: `
|
||||
script:
|
||||
- npm run deploy
|
||||
`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete a Rust function implementation inside a struct",
|
||||
|
|
@ -2168,4 +2135,70 @@ export default {
|
|||
llmOutput: "}",
|
||||
expectedCompletion: "}",
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should handle autocomplete in two similar TypeScript functions",
|
||||
filename: "List.svelte",
|
||||
input: `
|
||||
import { createClient, RedisClientType } from "redis";
|
||||
import { IKeyValueStore } from "./index.js";
|
||||
|
||||
export class RedisKeyValueStore implements IKeyValueStore {
|
||||
private client: RedisClientType;
|
||||
|
||||
constructor(redisUrl: string) {
|
||||
this.client = createClient({
|
||||
url: redisUrl
|
||||
.replace("https://", "redis://")
|
||||
.replace("http://", "redis://"),
|
||||
});
|
||||
this.client.on("connect", () => console.log("Redis Connected"));
|
||||
this.client.on("error", (err) => console.log("Redis Client Error", err));
|
||||
this.client.connect();
|
||||
}
|
||||
public async has(tableName: string, key: string): Promise<boolean> {
|
||||
return (await this.client.exists(this._getKey(tableName, key))) > 0;
|
||||
}
|
||||
|
||||
public async keys(tableName: string): Promise<string[]> {
|
||||
const keys = await this.client.keys(this._getTableKey(tableName));
|
||||
return keys.map((key) => key.split("::")[1]);
|
||||
}
|
||||
|
||||
public async put(
|
||||
tableName: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<void> {
|
||||
await this.client.set(this._getKey(tableName, key), value);
|
||||
}
|
||||
|
||||
public async get(
|
||||
tableName: string,
|
||||
key: string,
|
||||
): Promise<string | undefined> {
|
||||
const value = await this.client.get(this._getKey(tableName, key));
|
||||
return value ?? undefined;
|
||||
}
|
||||
|
||||
public async deleteAll(tableName: string): Promise<void> {
|
||||
await this.client.del(this._getTableKey(tableName));
|
||||
}
|
||||
|
||||
<|fim|>
|
||||
|
||||
|
||||
public async remove(tableName: string, key: string): Promise<boolean> {
|
||||
const result = await this.client.del(this._getKey(tableName, key));
|
||||
return result > 0;
|
||||
}
|
||||
}
|
||||
`,
|
||||
llmOutput: ` public async delete(tableName: string, key: string): Promise<void> {
|
||||
await this.client.del(this._getKey(tableName, key));
|
||||
}`,
|
||||
expectedCompletion: ` public async delete(tableName: string, key: string): Promise<void> {
|
||||
await this.client.del(this._getKey(tableName, key));
|
||||
}`,
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { jest } from "@jest/globals";
|
||||
|
||||
import { ListenableGenerator } from "./ListenableGenerator";
|
||||
|
||||
describe("ListenableGenerator", () => {
|
||||
|
|
|
|||
|
|
@ -43,11 +43,15 @@ function isExtremeRepetition(completion: string): boolean {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
export function isOnlyWhitespace(completion: string): boolean {
|
||||
function isOnlyWhitespace(completion: string): boolean {
|
||||
const whitespaceRegex = /^[\s]+$/;
|
||||
return whitespaceRegex.test(completion);
|
||||
}
|
||||
|
||||
function isBlank(completion: string): boolean {
|
||||
return completion.trim().length === 0;
|
||||
}
|
||||
|
||||
export function postprocessCompletion({
|
||||
completion,
|
||||
llm,
|
||||
|
|
@ -60,6 +64,11 @@ export function postprocessCompletion({
|
|||
suffix: string;
|
||||
}): string | undefined {
|
||||
// Don't return empty
|
||||
if (isBlank(completion)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Don't return whitespace
|
||||
if (isOnlyWhitespace(completion)) {
|
||||
return undefined;
|
||||
}
|
||||
|
|
@ -112,11 +121,8 @@ export function postprocessCompletion({
|
|||
// }
|
||||
|
||||
// If prefix ends with space and so does completion, then remove the space from completion
|
||||
if (
|
||||
prefix.split("\n").pop()?.trim() !== "" &&
|
||||
prefix.endsWith(" ") &&
|
||||
completion.startsWith(" ")
|
||||
) {
|
||||
|
||||
if (prefix.endsWith(" ") && completion.startsWith(" ")) {
|
||||
completion = completion.slice(1);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ export const getSnippets = (
|
|||
...payload.clipboardSnippets,
|
||||
...shuffleArray(
|
||||
filterSnippetsAlreadyInCaretWindow(
|
||||
[...payload.rootPathSnippets],
|
||||
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
|
||||
helper.prunedCaretWindow,
|
||||
),
|
||||
),
|
||||
|
|
|
|||
|
|
@ -13,12 +13,14 @@ const getCommentMark = (helper: HelperVars) => {
|
|||
};
|
||||
|
||||
const addCommentMarks = (text: string, helper: HelperVars) => {
|
||||
const commentMark = getCommentMark(helper);
|
||||
const lines = [
|
||||
...text
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => `${getCommentMark(helper)} ${line}`),
|
||||
.map((line) => `${commentMark} ${line}`),
|
||||
];
|
||||
|
||||
return lines.join("\n");
|
||||
};
|
||||
|
||||
|
|
@ -61,11 +63,6 @@ const commentifySnippet = (
|
|||
};
|
||||
};
|
||||
|
||||
const SNIPPET_TYPES_TO_COMMENT = [
|
||||
AutocompleteSnippetType.Code,
|
||||
AutocompleteSnippetType.Clipboard,
|
||||
];
|
||||
|
||||
export const formatSnippets = (
|
||||
helper: HelperVars,
|
||||
snippets: AutocompleteSnippet[],
|
||||
|
|
@ -88,19 +85,7 @@ export const formatSnippets = (
|
|||
}
|
||||
})
|
||||
.map((item) => {
|
||||
if (SNIPPET_TYPES_TO_COMMENT.includes(item.type)) {
|
||||
return commentifySnippet(helper, item);
|
||||
}
|
||||
|
||||
return item;
|
||||
})
|
||||
.map((item) => {
|
||||
if (SNIPPET_TYPES_TO_COMMENT.includes(item.type)) {
|
||||
const commentMark = getCommentMark(helper);
|
||||
return item.content + `\n${commentMark}\n${commentMark}`;
|
||||
}
|
||||
|
||||
return item.content;
|
||||
return commentifySnippet(helper, item).content;
|
||||
})
|
||||
.join("\n") + `\n${currentFilepathComment}`
|
||||
);
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ const STARCODER2_T_ARTIFACTS = ["t.", "\nt", "<file_sep>"];
|
|||
const PYTHON_ENCODING = "#- coding: utf-8";
|
||||
const CODE_BLOCK_END = "```";
|
||||
|
||||
const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE];
|
||||
// const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE];
|
||||
const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END];
|
||||
|
||||
export function getStopTokens(
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ import {
|
|||
getTemplateForModel,
|
||||
} from "./AutocompleteTemplate";
|
||||
import { getStopTokens } from "./getStopTokens";
|
||||
import { AutocompleteCodeSnippet } from "../snippets/types";
|
||||
import { SnippetPayload } from "../snippets";
|
||||
import { formatSnippets } from "./formatting";
|
||||
import { getSnippets } from "./filtering";
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
|
||||
import { stripImages } from "../llm/images";
|
||||
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
|
||||
import { renderChatMessage } from "../util/messageContent";
|
||||
|
||||
import SlashCommands from "./slash";
|
||||
|
||||
|
|
@ -29,7 +29,8 @@ export function slashFromCustomCommand(
|
|||
const messages = [...history];
|
||||
// Find the last chat message with this slash command and replace it with the user input
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const { role, content } = messages[i];
|
||||
const message = messages[i];
|
||||
const { role, content } = message;
|
||||
if (role !== "user") {
|
||||
continue;
|
||||
}
|
||||
|
|
@ -41,7 +42,7 @@ export function slashFromCustomCommand(
|
|||
)
|
||||
) {
|
||||
messages[i] = {
|
||||
...messages[i],
|
||||
...message,
|
||||
content: content.map((part) => {
|
||||
return part.text?.startsWith(`/${customCommand.name}`)
|
||||
? { ...part, text: promptUserInput }
|
||||
|
|
@ -53,13 +54,16 @@ export function slashFromCustomCommand(
|
|||
typeof content === "string" &&
|
||||
content.startsWith(`/${customCommand.name}`)
|
||||
) {
|
||||
messages[i] = { ...messages[i], content: promptUserInput };
|
||||
messages[i] = { ...message, content: promptUserInput };
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for await (const chunk of llm.streamChat(messages, new AbortController().signal)) {
|
||||
yield stripImages(chunk.content);
|
||||
for await (const chunk of llm.streamChat(
|
||||
messages,
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,19 +0,0 @@
|
|||
import { SlashCommand } from "../../";
|
||||
|
||||
import EditSlashCommand from "./edit";
|
||||
|
||||
const CommentSlashCommand: SlashCommand = {
|
||||
name: "comment",
|
||||
description: "Write comments for highlighted code",
|
||||
run: async function* (sdk) {
|
||||
for await (const update of EditSlashCommand.run({
|
||||
...sdk,
|
||||
input:
|
||||
"Write comments for this code. Do not change anything about the code itself.",
|
||||
})) {
|
||||
yield update;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export default CommentSlashCommand;
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { SlashCommand } from "../../index.js";
|
||||
import { stripImages } from "../../llm/images.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
|
||||
const CommitMessageCommand: SlashCommand = {
|
||||
name: "commit",
|
||||
|
|
@ -18,7 +18,7 @@ const CommitMessageCommand: SlashCommand = {
|
|||
[{ role: "user", content: prompt }],
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
yield stripImages(chunk.content);
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { ChatMessage, SlashCommand } from "../../index.js";
|
||||
import { stripImages } from "../../llm/images.js";
|
||||
import { removeQuotesAndEscapes } from "../../util/index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
|
||||
const PROMPT = (
|
||||
input: string,
|
||||
|
|
@ -30,7 +30,8 @@ const DraftIssueCommand: SlashCommand = {
|
|||
return;
|
||||
}
|
||||
let title = await llm.complete(
|
||||
`Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, new AbortController().signal,
|
||||
`Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `,
|
||||
new AbortController().signal,
|
||||
{ maxTokens: 20 },
|
||||
);
|
||||
|
||||
|
|
@ -43,9 +44,12 @@ const DraftIssueCommand: SlashCommand = {
|
|||
{ role: "user", content: PROMPT(input, title) },
|
||||
];
|
||||
|
||||
for await (const chunk of llm.streamChat(messages, new AbortController().signal)) {
|
||||
for await (const chunk of llm.streamChat(
|
||||
messages,
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
body += chunk.content;
|
||||
yield stripImages(chunk.content);
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
|
||||
const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent(
|
||||
|
|
|
|||
|
|
@ -1,637 +0,0 @@
|
|||
import {
|
||||
ContextItemWithId,
|
||||
ILLM,
|
||||
RangeInFileWithContents,
|
||||
SlashCommand,
|
||||
} from "../../";
|
||||
import {
|
||||
filterCodeBlockLines,
|
||||
filterEnglishLinesAtEnd,
|
||||
filterEnglishLinesAtStart,
|
||||
fixCodeLlamaFirstLineIndentation,
|
||||
stopAtLines,
|
||||
streamWithNewLines,
|
||||
} from "../../autocomplete/filtering/streamTransforms/lineStream";
|
||||
import { streamLines } from "../../diff/util";
|
||||
import { stripImages } from "../../llm/images";
|
||||
import {
|
||||
dedentAndGetCommonWhitespace,
|
||||
getMarkdownLanguageTagForFile,
|
||||
} from "../../util/";
|
||||
import { ctxItemToRifWithContents } from "../util";
|
||||
|
||||
const PROMPT = `Take the file prefix and suffix into account, but only rewrite the code_to_edit as specified in the user_request. The code you write in modified_code_to_edit will replace the code between the code_to_edit tags. Do NOT preface your answer or write anything other than code. The </modified_code_to_edit> tag should be written to indicate the end of the modified code section. Do not ever use nested tags.
|
||||
|
||||
Example:
|
||||
|
||||
<file_prefix>
|
||||
class Database:
|
||||
def __init__(self):
|
||||
self._data = {{}}
|
||||
|
||||
def get(self, key):
|
||||
return self._data[key]
|
||||
|
||||
</file_prefix>
|
||||
<code_to_edit>
|
||||
def set(self, key, value):
|
||||
self._data[key] = value
|
||||
</code_to_edit>
|
||||
<file_suffix>
|
||||
|
||||
def clear_all():
|
||||
self._data = {{}}
|
||||
</file_suffix>
|
||||
<user_request>
|
||||
Raise an error if the key already exists.
|
||||
</user_request>
|
||||
<modified_code_to_edit>
|
||||
def set(self, key, value):
|
||||
if key in self._data:
|
||||
raise KeyError(f"Key {{key}} already exists")
|
||||
self._data[key] = value
|
||||
</modified_code_to_edit>
|
||||
|
||||
Main task:
|
||||
`;
|
||||
|
||||
export async function getPromptParts(
|
||||
rif: RangeInFileWithContents,
|
||||
fullFileContents: string,
|
||||
model: ILLM,
|
||||
input: string,
|
||||
tokenLimit: number | undefined,
|
||||
) {
|
||||
const maxTokens = Math.floor(model.contextLength / 2);
|
||||
|
||||
const BUFFER_FOR_FUNCTIONS = 400;
|
||||
let totalTokens =
|
||||
model.countTokens(fullFileContents + PROMPT + input) +
|
||||
BUFFER_FOR_FUNCTIONS +
|
||||
maxTokens;
|
||||
|
||||
const fullFileContentsList = fullFileContents.split("\n");
|
||||
const maxStartLine = rif.range.start.line;
|
||||
const minEndLine = rif.range.end.line;
|
||||
let curStartLine = 0;
|
||||
let curEndLine = fullFileContentsList.length - 1;
|
||||
|
||||
if (totalTokens > model.contextLength) {
|
||||
while (curEndLine > minEndLine) {
|
||||
totalTokens -= model.countTokens(fullFileContentsList[curEndLine]);
|
||||
curEndLine--;
|
||||
if (totalTokens < model.contextLength) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (totalTokens > model.contextLength) {
|
||||
while (curStartLine < maxStartLine) {
|
||||
curStartLine++;
|
||||
totalTokens -= model.countTokens(fullFileContentsList[curStartLine]);
|
||||
if (totalTokens < model.contextLength) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let filePrefix = fullFileContentsList
|
||||
.slice(curStartLine, maxStartLine - 1)
|
||||
.join("\n");
|
||||
let fileSuffix = fullFileContentsList
|
||||
.slice(minEndLine, curEndLine + 1)
|
||||
.join("\n");
|
||||
|
||||
if (rif.contents.length > 0) {
|
||||
let lines = rif.contents.split(/\r?\n/);
|
||||
let firstLine = lines[0] || null;
|
||||
while (firstLine && firstLine.trim() === "") {
|
||||
filePrefix += firstLine;
|
||||
rif.contents = rif.contents.substring(firstLine.length);
|
||||
lines = rif.contents.split(/\r?\n/);
|
||||
firstLine = lines[0] || null;
|
||||
}
|
||||
|
||||
let lastLine = lines[lines.length - 1] || null;
|
||||
while (lastLine && lastLine.trim() === "") {
|
||||
fileSuffix = lastLine + fileSuffix;
|
||||
rif.contents = rif.contents.substring(
|
||||
0,
|
||||
rif.contents.length - lastLine.length,
|
||||
);
|
||||
lines = rif.contents.split(/\r?\n/);
|
||||
lastLine = lines[lines.length - 1] || null;
|
||||
}
|
||||
|
||||
while (rif.contents.startsWith("\n")) {
|
||||
filePrefix += "\n";
|
||||
rif.contents = rif.contents.substring(1);
|
||||
}
|
||||
while (rif.contents.endsWith("\n")) {
|
||||
fileSuffix = `\n${fileSuffix}`;
|
||||
rif.contents = rif.contents.substring(0, rif.contents.length - 1);
|
||||
}
|
||||
}
|
||||
return { filePrefix, fileSuffix, contents: rif.contents, maxTokens };
|
||||
}
|
||||
|
||||
function compilePrompt(
|
||||
filePrefix: string,
|
||||
contents: string,
|
||||
fileSuffix: string,
|
||||
input: string,
|
||||
): string {
|
||||
if (contents.trim() === "") {
|
||||
// Separate prompt for insertion at the cursor, the other tends to cause it to repeat whole file
|
||||
return `\
|
||||
<file_prefix>
|
||||
${filePrefix}
|
||||
</file_prefix>
|
||||
<insertion_code_here>
|
||||
<file_suffix>
|
||||
${fileSuffix}
|
||||
</file_suffix>
|
||||
<user_request>
|
||||
${input}
|
||||
</user_request>
|
||||
|
||||
Please output the code to be inserted at the cursor in order to fulfill the user_request. Do NOT preface your answer or write anything other than code. You should not write any tags, just the code. Make sure to correctly indent the code:`;
|
||||
}
|
||||
|
||||
let prompt = PROMPT;
|
||||
if (filePrefix.trim() !== "") {
|
||||
prompt += `
|
||||
<file_prefix>
|
||||
${filePrefix}
|
||||
</file_prefix>`;
|
||||
}
|
||||
prompt += `
|
||||
<code_to_edit>
|
||||
${contents}
|
||||
</code_to_edit>`;
|
||||
|
||||
if (fileSuffix.trim() !== "") {
|
||||
prompt += `
|
||||
<file_suffix>
|
||||
${fileSuffix}
|
||||
</file_suffix>`;
|
||||
}
|
||||
prompt += `
|
||||
<user_request>
|
||||
${input}
|
||||
</user_request>
|
||||
<modified_code_to_edit>
|
||||
`;
|
||||
|
||||
return prompt;
|
||||
}
|
||||
|
||||
function isEndLine(line: string) {
|
||||
return (
|
||||
line.includes("</modified_code_to_edit>") ||
|
||||
line.includes("</code_to_edit>") ||
|
||||
line.includes("[/CODE]")
|
||||
);
|
||||
}
|
||||
|
||||
function lineToBeIgnored(line: string, isFirstLine = false): boolean {
|
||||
return (
|
||||
line.includes("```") ||
|
||||
line.includes("<modified_code_to_edit>") ||
|
||||
line.includes("<file_prefix>") ||
|
||||
line.includes("</file_prefix>") ||
|
||||
line.includes("<file_suffix>") ||
|
||||
line.includes("</file_suffix>") ||
|
||||
line.includes("<user_request>") ||
|
||||
line.includes("</user_request>") ||
|
||||
line.includes("<code_to_edit>")
|
||||
);
|
||||
}
|
||||
|
||||
const EditSlashCommand: SlashCommand = {
|
||||
name: "edit",
|
||||
description: "Edit selected code",
|
||||
run: async function* ({ ide, llm, input, history, contextItems, params }) {
|
||||
let contextItemToEdit = contextItems.find(
|
||||
(item: ContextItemWithId) =>
|
||||
item.editing && item.id.providerTitle === "code",
|
||||
);
|
||||
if (!contextItemToEdit) {
|
||||
contextItemToEdit = contextItems.find(
|
||||
(item: ContextItemWithId) => item.id.providerTitle === "code",
|
||||
);
|
||||
}
|
||||
|
||||
if (!contextItemToEdit) {
|
||||
yield "Please highlight the code you want to edit, then press `cmd/ctrl+shift+L` to add it to chat";
|
||||
return;
|
||||
}
|
||||
|
||||
// Strip unecessary parts of the input (the fact that you have to do this is suboptimal, should be refactored away)
|
||||
let content = history[history.length - 1].content;
|
||||
if (typeof content !== "string") {
|
||||
content.forEach((part) => {
|
||||
if (part.text?.startsWith("/edit")) {
|
||||
part.text = part.text.replace("/edit", "").trimStart();
|
||||
}
|
||||
});
|
||||
} else if (input?.startsWith("/edit")) {
|
||||
content = input.replace("/edit", "").trimStart();
|
||||
} else if (input?.startsWith("/comment")) {
|
||||
content = input.replace("/comment", "").trimStart();
|
||||
}
|
||||
let userInput = stripImages(content).replace(
|
||||
`\`\`\`${contextItemToEdit.name}\n${contextItemToEdit.content}\n\`\`\`\n`,
|
||||
"",
|
||||
);
|
||||
// if the above replace fails to find a match, the code will still be present
|
||||
// in the userInput. Replace it with input if available.
|
||||
if (userInput.includes("```") && (input !== "" || !input)) {
|
||||
userInput = input;
|
||||
}
|
||||
|
||||
const rif: RangeInFileWithContents =
|
||||
ctxItemToRifWithContents(contextItemToEdit);
|
||||
|
||||
await ide.saveFile(rif.filepath);
|
||||
const fullFileContents = await ide.readFile(rif.filepath);
|
||||
|
||||
let { filePrefix, contents, fileSuffix, maxTokens } = await getPromptParts(
|
||||
rif,
|
||||
fullFileContents,
|
||||
llm,
|
||||
userInput,
|
||||
params?.tokenLimit,
|
||||
);
|
||||
const [dedentedContents, commonWhitespace] =
|
||||
dedentAndGetCommonWhitespace(contents);
|
||||
contents = dedentedContents;
|
||||
|
||||
const prompt = compilePrompt(filePrefix, contents, fileSuffix, userInput);
|
||||
const fullFileContentsLines = fullFileContents.split("\n");
|
||||
const fullPrefixLines = fullFileContentsLines.slice(
|
||||
0,
|
||||
Math.max(0, rif.range.start.line - 1),
|
||||
);
|
||||
const fullSuffixLines = fullFileContentsLines.slice(rif.range.end.line);
|
||||
|
||||
let linesToDisplay: string[] = [];
|
||||
|
||||
async function sendDiffUpdate(lines: string[], final = false) {
|
||||
const completion = lines.join("\n");
|
||||
|
||||
// Don't do this at the very end, just show the inserted code
|
||||
if (final) {
|
||||
linesToDisplay = [];
|
||||
}
|
||||
|
||||
// Only recalculate at every new-line, because this is sort of expensive
|
||||
else if (completion.endsWith("\n")) {
|
||||
const contentsLines = rif.contents.split("\n");
|
||||
let rewrittenLines = 0;
|
||||
for (const line of lines) {
|
||||
for (let i = rewrittenLines; i < contentsLines.length; i++) {
|
||||
if (
|
||||
// difflib.SequenceMatcher(
|
||||
// null, line, contentsLines[i]
|
||||
// ).ratio()
|
||||
// > 0.7
|
||||
line.trim() === contentsLines[i].trim() && // Temp replacement for difflib (TODO)
|
||||
contentsLines[i].trim() !== ""
|
||||
) {
|
||||
rewrittenLines = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
linesToDisplay = contentsLines.slice(rewrittenLines);
|
||||
}
|
||||
|
||||
const newFileContents = `${fullPrefixLines.join("\n")}\n${completion}\n${
|
||||
linesToDisplay.length > 0 ? `${linesToDisplay.join("\n")}\n` : ""
|
||||
}${fullSuffixLines.join("\n")}`;
|
||||
|
||||
const stepIndex = history.length - 1;
|
||||
|
||||
await ide.showDiff(rif.filepath, newFileContents, stepIndex);
|
||||
}
|
||||
|
||||
// Important state variables
|
||||
// -------------------------
|
||||
const originalLines = rif.contents === "" ? [] : rif.contents.split("\n");
|
||||
// In the actual file, taking into account block offset
|
||||
let currentLineInFile = rif.range.start.line;
|
||||
let currentBlockLines: string[] = [];
|
||||
let originalLinesBelowPreviousBlocks = originalLines;
|
||||
// The start of the current block in file, taking into account block offset
|
||||
let currentBlockStart = -1;
|
||||
let offsetFromBlocks = 0;
|
||||
|
||||
// Don't end the block until you've matched N simultaneous lines
|
||||
// This helps avoid many tiny blocks
|
||||
const LINES_TO_MATCH_BEFORE_ENDING_BLOCK = 2;
|
||||
// If a line has been matched at the end of the block, this is its index within originalLinesBelowPreviousBlocks
|
||||
// Except we are keeping track of multiple potentialities, so it's a list
|
||||
// We always check the lines following each of these leads, but if multiple make it out at the end, we use the first one
|
||||
// This is a tuple of (index_of_last_matched_line, number_of_lines_matched)
|
||||
let indicesOfLastMatchedLines: [number, number][] = [];
|
||||
|
||||
async function handleGeneratedLine(line: string) {
|
||||
if (currentBlockLines.length === 0) {
|
||||
// Set this as the start of the next block
|
||||
currentBlockStart =
|
||||
rif.range.start.line +
|
||||
originalLines.length -
|
||||
originalLinesBelowPreviousBlocks.length +
|
||||
offsetFromBlocks;
|
||||
if (
|
||||
originalLinesBelowPreviousBlocks.length > 0 &&
|
||||
line === originalLinesBelowPreviousBlocks[0]
|
||||
) {
|
||||
// Line is equal to the next line in file, move past this line
|
||||
originalLinesBelowPreviousBlocks =
|
||||
originalLinesBelowPreviousBlocks.slice(1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// In a block, and have already matched at least one line
|
||||
// Check if the next line matches, for each of the candidates
|
||||
const matchesFound: any[] = [];
|
||||
let firstValidMatch: any = null;
|
||||
for (const [
|
||||
index_of_last_matched_line,
|
||||
num_lines_matched,
|
||||
] of indicesOfLastMatchedLines) {
|
||||
if (
|
||||
index_of_last_matched_line + 1 <
|
||||
originalLinesBelowPreviousBlocks.length &&
|
||||
line ===
|
||||
originalLinesBelowPreviousBlocks[index_of_last_matched_line + 1]
|
||||
) {
|
||||
matchesFound.push([
|
||||
index_of_last_matched_line + 1,
|
||||
num_lines_matched + 1,
|
||||
]);
|
||||
if (
|
||||
firstValidMatch === null &&
|
||||
num_lines_matched + 1 >= LINES_TO_MATCH_BEFORE_ENDING_BLOCK
|
||||
) {
|
||||
firstValidMatch = [
|
||||
index_of_last_matched_line + 1,
|
||||
num_lines_matched + 1,
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
indicesOfLastMatchedLines = matchesFound;
|
||||
|
||||
if (firstValidMatch !== null) {
|
||||
// We've matched the required number of lines, insert suggestion!
|
||||
|
||||
// We added some lines to the block that were matched (including maybe some blank lines)
|
||||
// So here we will strip all matching lines from the end of currentBlockLines
|
||||
const linesStripped: string[] = [];
|
||||
let indexOfLastLineInBlock: number = firstValidMatch[0];
|
||||
while (
|
||||
currentBlockLines.length > 0 &&
|
||||
currentBlockLines[currentBlockLines.length - 1] ===
|
||||
originalLinesBelowPreviousBlocks[indexOfLastLineInBlock - 1]
|
||||
) {
|
||||
linesStripped.push(currentBlockLines.pop() as string);
|
||||
indexOfLastLineInBlock -= 1;
|
||||
}
|
||||
|
||||
// Reset current block / update variables
|
||||
currentLineInFile += 1;
|
||||
offsetFromBlocks += currentBlockLines.length;
|
||||
originalLinesBelowPreviousBlocks =
|
||||
originalLinesBelowPreviousBlocks.slice(indexOfLastLineInBlock + 1);
|
||||
currentBlockLines = [];
|
||||
currentBlockStart = -1;
|
||||
indicesOfLastMatchedLines = [];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Always look for new matching candidates
|
||||
const newMatches: any[] = [];
|
||||
for (let i = 0; i < originalLinesBelowPreviousBlocks.length; i++) {
|
||||
const ogLine = originalLinesBelowPreviousBlocks[i];
|
||||
// TODO: It's a bit sus to be disqualifying empty lines.
|
||||
// What you ideally do is find ALL matches, and then throw them out as you check the following lines
|
||||
if (ogLine === line) {
|
||||
// and og_line.trim() !== "":
|
||||
newMatches.push([i, 1]);
|
||||
}
|
||||
}
|
||||
indicesOfLastMatchedLines = indicesOfLastMatchedLines.concat(newMatches);
|
||||
|
||||
// Make sure they are sorted by index
|
||||
indicesOfLastMatchedLines = indicesOfLastMatchedLines.sort(
|
||||
(a, b) => a[0] - b[0],
|
||||
);
|
||||
|
||||
currentBlockLines.push(line);
|
||||
}
|
||||
|
||||
let messages = history;
|
||||
messages[messages.length - 1] = { role: "user", content: prompt };
|
||||
|
||||
let linesOfPrefixCopied = 0;
|
||||
const lines = [];
|
||||
let unfinishedLine = "";
|
||||
let completionLinesCovered = 0;
|
||||
let repeatingFileSuffix = false;
|
||||
const lineBelowHighlightedRange = fileSuffix.trim().split("\n")[0];
|
||||
|
||||
// Use custom templates defined by the model
|
||||
const template = llm.promptTemplates?.edit;
|
||||
let generator: AsyncGenerator<string>;
|
||||
if (template) {
|
||||
const rendered = llm.renderPromptTemplate(
|
||||
template,
|
||||
// typeof template === 'string' ? template : template.prompt,
|
||||
messages.slice(0, messages.length - 1),
|
||||
{
|
||||
codeToEdit: rif.contents,
|
||||
userInput,
|
||||
filePrefix: filePrefix,
|
||||
fileSuffix: fileSuffix,
|
||||
|
||||
// Some built-in templates use these instead of the above
|
||||
prefix: filePrefix,
|
||||
suffix: fileSuffix,
|
||||
|
||||
language: getMarkdownLanguageTagForFile(rif.filepath),
|
||||
systemMessage: llm.systemMessage ?? "",
|
||||
// "contextItems": (await sdk.getContextItemChatMessages()).map(x => x.content || "").join("\n\n"),
|
||||
},
|
||||
);
|
||||
if (typeof rendered === "string") {
|
||||
messages = [
|
||||
{
|
||||
role: "user",
|
||||
content: rendered,
|
||||
},
|
||||
];
|
||||
} else {
|
||||
messages = rendered;
|
||||
}
|
||||
|
||||
const completion = llm.streamComplete(
|
||||
rendered as string,
|
||||
new AbortController().signal,
|
||||
{
|
||||
maxTokens: Math.min(
|
||||
maxTokens,
|
||||
Math.floor(llm.contextLength / 2),
|
||||
4096,
|
||||
),
|
||||
raw: true,
|
||||
},
|
||||
);
|
||||
let lineStream = streamLines(completion);
|
||||
|
||||
lineStream = filterEnglishLinesAtStart(lineStream);
|
||||
|
||||
lineStream = filterEnglishLinesAtEnd(filterCodeBlockLines(lineStream));
|
||||
lineStream = stopAtLines(lineStream, () => {});
|
||||
|
||||
generator = streamWithNewLines(
|
||||
fixCodeLlamaFirstLineIndentation(lineStream),
|
||||
);
|
||||
} else {
|
||||
async function* gen() {
|
||||
for await (const chunk of llm.streamChat(
|
||||
messages,
|
||||
new AbortController().signal,
|
||||
{
|
||||
temperature: 0.5, // TODO
|
||||
maxTokens: Math.min(
|
||||
maxTokens,
|
||||
Math.floor(llm.contextLength / 2),
|
||||
4096,
|
||||
),
|
||||
},
|
||||
)) {
|
||||
yield stripImages(chunk.content);
|
||||
}
|
||||
}
|
||||
|
||||
generator = gen();
|
||||
}
|
||||
|
||||
for await (const chunk of generator) {
|
||||
// Stop early if it is repeating the fileSuffix or the step was deleted
|
||||
if (repeatingFileSuffix) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Allow stopping breakpoints
|
||||
yield undefined;
|
||||
|
||||
// Accumulate lines
|
||||
const chunkLines = chunk.split("\n");
|
||||
chunkLines[0] = unfinishedLine + chunkLines[0];
|
||||
if (chunk.endsWith("\n")) {
|
||||
unfinishedLine = "";
|
||||
chunkLines.pop(); // because this will be an empty string
|
||||
} else {
|
||||
unfinishedLine = chunkLines.pop() ?? "";
|
||||
}
|
||||
|
||||
// Deal with newly accumulated lines
|
||||
for (let i = 0; i < chunkLines.length; i++) {
|
||||
// Trailing whitespace doesn't matter
|
||||
chunkLines[i] = chunkLines[i].trimEnd();
|
||||
chunkLines[i] = commonWhitespace + chunkLines[i];
|
||||
|
||||
// Lines that should signify the end of generation
|
||||
if (isEndLine(chunkLines[i])) {
|
||||
break;
|
||||
}
|
||||
// Lines that should be ignored, like the <> tags
|
||||
if (lineToBeIgnored(chunkLines[i], completionLinesCovered === 0)) {
|
||||
continue; // noice
|
||||
}
|
||||
// Check if we are currently just copying the prefix
|
||||
if (
|
||||
(linesOfPrefixCopied > 0 || completionLinesCovered === 0) &&
|
||||
linesOfPrefixCopied < filePrefix.split("\n").length &&
|
||||
chunkLines[i] === fullPrefixLines[linesOfPrefixCopied]
|
||||
) {
|
||||
// This is a sketchy way of stopping it from repeating the filePrefix. Is a bug if output happens to have a matching line
|
||||
linesOfPrefixCopied += 1;
|
||||
continue; // also nice
|
||||
}
|
||||
// Because really short lines might be expected to be repeated, this is only a !heuristic!
|
||||
// Stop when it starts copying the fileSuffix
|
||||
if (
|
||||
chunkLines[i].trim() === lineBelowHighlightedRange.trim() &&
|
||||
chunkLines[i].trim().length > 4 &&
|
||||
!(
|
||||
originalLinesBelowPreviousBlocks.length > 0 &&
|
||||
chunkLines[i].trim() === originalLinesBelowPreviousBlocks[0].trim()
|
||||
)
|
||||
) {
|
||||
repeatingFileSuffix = true;
|
||||
break;
|
||||
}
|
||||
|
||||
lines.push(chunkLines[i]);
|
||||
completionLinesCovered += 1;
|
||||
currentLineInFile += 1;
|
||||
}
|
||||
|
||||
await sendDiffUpdate(
|
||||
lines.concat([
|
||||
unfinishedLine?.startsWith("<")
|
||||
? commonWhitespace
|
||||
: commonWhitespace + unfinishedLine,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
// Add the unfinished line
|
||||
if (
|
||||
unfinishedLine !== "" &&
|
||||
!lineToBeIgnored(unfinishedLine, completionLinesCovered === 0) &&
|
||||
!isEndLine(unfinishedLine)
|
||||
) {
|
||||
unfinishedLine = commonWhitespace + unfinishedLine;
|
||||
lines.push(unfinishedLine);
|
||||
await handleGeneratedLine(unfinishedLine);
|
||||
completionLinesCovered += 1;
|
||||
currentLineInFile += 1;
|
||||
}
|
||||
|
||||
await sendDiffUpdate(lines, true);
|
||||
|
||||
if (params?.recap) {
|
||||
const prompt = `This is the code before editing:
|
||||
\`\`\`
|
||||
${contents}
|
||||
\`\`\`
|
||||
|
||||
This is the code after editing:
|
||||
|
||||
\`\`\`
|
||||
${lines.join("\n")}
|
||||
\`\`\`
|
||||
|
||||
Please briefly explain the changes made to the code above. Give no more than 2-3 sentences, and use markdown bullet points:`;
|
||||
|
||||
for await (const update of llm.streamComplete(
|
||||
prompt,
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
yield update;
|
||||
}
|
||||
}
|
||||
yield `Edited ${contextItemToEdit.name}`;
|
||||
},
|
||||
};
|
||||
|
||||
export default EditSlashCommand;
|
||||
46
core/commands/slash/mcp.ts
Normal file
46
core/commands/slash/mcp.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
|
||||
import { ChatMessage, SlashCommand } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
export function constructMcpSlashCommand(
|
||||
client: Client,
|
||||
name: string,
|
||||
description?: string,
|
||||
args?: string[],
|
||||
): SlashCommand {
|
||||
return {
|
||||
name,
|
||||
description: description ?? "MCP Prompt",
|
||||
params: {},
|
||||
run: async function* (context) {
|
||||
const argsObject: { [key: string]: string } = {};
|
||||
const userInput = context.input.split(" ").slice(1).join(" ");
|
||||
if (args) {
|
||||
args.forEach((arg, i) => {
|
||||
argsObject[arg] = userInput;
|
||||
});
|
||||
}
|
||||
|
||||
const result = await client.getPrompt({ name, arguments: argsObject });
|
||||
|
||||
const messages: ChatMessage[] = result.messages.map((msg) => {
|
||||
if (msg.content.type !== "text") {
|
||||
throw new Error(
|
||||
"Continue currently only supports text prompts through MCP",
|
||||
);
|
||||
}
|
||||
return {
|
||||
content: msg.content.text,
|
||||
role: msg.role,
|
||||
};
|
||||
});
|
||||
|
||||
for await (const chunk of context.llm.streamChat(
|
||||
messages,
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -9,7 +9,7 @@ import {
|
|||
defaultIgnoreFile,
|
||||
gitIgArrayFromFile,
|
||||
} from "../../indexing/ignore";
|
||||
import { stripImages } from "../../llm/images";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
|
||||
const LANGUAGE_DEP_MGMT_FILENAMES = [
|
||||
"package.json", // JavaScript (Node.js)
|
||||
|
|
@ -45,10 +45,11 @@ const OnboardSlashCommand: SlashCommand = {
|
|||
const context = await gatherProjectContext(workspaceDir, ide);
|
||||
const prompt = createOnboardingPrompt(context);
|
||||
|
||||
for await (const chunk of llm.streamChat([
|
||||
{ role: "user", content: prompt },
|
||||
], new AbortController().signal)) {
|
||||
yield stripImages(chunk.content);
|
||||
for await (const chunk of llm.streamChat(
|
||||
[{ role: "user", content: prompt }],
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ChatMessage, SlashCommand } from "../../index.js";
|
||||
import { stripImages } from "../../llm/images.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
|
||||
const prompt = `
|
||||
Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines:
|
||||
|
|
@ -43,10 +43,11 @@ const ReviewMessageCommand: SlashCommand = {
|
|||
|
||||
const content = `${prompt} \r\n ${reviewText}`;
|
||||
|
||||
for await (const chunk of llm.streamChat([
|
||||
{ role: "user", content: content },
|
||||
], new AbortController().signal)) {
|
||||
yield stripImages(chunk.content);
|
||||
for await (const chunk of llm.streamChat(
|
||||
[{ role: "user", content: content }],
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import path from "path";
|
|||
|
||||
import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js";
|
||||
import { SlashCommand } from "../../index.js";
|
||||
import { stripImages } from "../../llm/images.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
|
||||
// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
|
||||
function getOffsetDatetime(date: Date): Date {
|
||||
|
|
@ -48,7 +48,7 @@ const ShareSlashCommand: SlashCommand = {
|
|||
// message in the chat history, this will omit it
|
||||
for (const msg of history.slice(0, history.length - 1)) {
|
||||
let msgText = msg.content;
|
||||
msgText = stripImages(msg.content);
|
||||
msgText = renderChatMessage(msg);
|
||||
|
||||
if (msg.role === "user" && msgText.search("```") > -1) {
|
||||
msgText = reformatCodeBlocks(msgText);
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
import { execSync } from "child_process";
|
||||
import * as JSONC from "comment-json";
|
||||
import * as fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
|
||||
import * as JSONC from "comment-json";
|
||||
import * as tar from "tar";
|
||||
|
||||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
Config,
|
||||
|
|
@ -28,6 +29,7 @@ import {
|
|||
slashCommandFromDescription,
|
||||
slashFromCustomCommand,
|
||||
} from "../commands/index.js";
|
||||
import MCPConnectionSingleton from "../context/mcp";
|
||||
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
|
||||
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
|
||||
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
|
||||
|
|
@ -42,6 +44,7 @@ import { BaseLLM } from "../llm";
|
|||
import { llmFromDescription } from "../llm/llms";
|
||||
import CustomLLMClass from "../llm/llms/CustomLLM";
|
||||
import FreeTrial from "../llm/llms/FreeTrial";
|
||||
import { allTools } from "../tools";
|
||||
import { copyOf } from "../util";
|
||||
import { fetchwithRequestOptions } from "../util/fetchWithOptions";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
|
|
@ -57,7 +60,6 @@ import {
|
|||
getEsbuildBinaryPath,
|
||||
readAllGlobalPromptFiles,
|
||||
} from "../util/paths";
|
||||
|
||||
import {
|
||||
defaultContextProvidersJetBrains,
|
||||
defaultContextProvidersVsCode,
|
||||
|
|
@ -484,14 +486,36 @@ async function intermediateToFinalConfig(
|
|||
}
|
||||
}
|
||||
|
||||
return {
|
||||
let continueConfig: ContinueConfig = {
|
||||
...config,
|
||||
contextProviders,
|
||||
models,
|
||||
embeddingsProvider: config.embeddingsProvider as any,
|
||||
tabAutocompleteModels,
|
||||
reranker: config.reranker as any,
|
||||
tools: allTools,
|
||||
};
|
||||
|
||||
// Apply MCP if specified
|
||||
if (config.experimental?.modelContextProtocolServer) {
|
||||
const mcpConnection = await MCPConnectionSingleton.getInstance(
|
||||
config.experimental.modelContextProtocolServer,
|
||||
);
|
||||
continueConfig = await Promise.race<ContinueConfig>([
|
||||
mcpConnection.modifyConfig(continueConfig),
|
||||
new Promise((_, reject) =>
|
||||
setTimeout(
|
||||
() => reject(new Error("MCP connection timed out after 2000ms")),
|
||||
2000,
|
||||
),
|
||||
),
|
||||
]).catch((error) => {
|
||||
console.warn("MCP connection error:", error);
|
||||
return continueConfig; // Return original config if timeout occurs
|
||||
});
|
||||
}
|
||||
|
||||
return continueConfig;
|
||||
}
|
||||
|
||||
function finalToBrowserConfig(
|
||||
|
|
@ -528,6 +552,7 @@ function finalToBrowserConfig(
|
|||
ui: final.ui,
|
||||
experimental: final.experimental,
|
||||
docs: final.docs,
|
||||
tools: final.tools,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,9 +4,9 @@ import Handlebars from "handlebars";
|
|||
import * as YAML from "yaml";
|
||||
|
||||
import { walkDir } from "../indexing/walkDir";
|
||||
import { stripImages } from "../llm/images";
|
||||
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
|
||||
import { getBasename } from "../util/index";
|
||||
import { renderChatMessage } from "../util/messageContent";
|
||||
|
||||
import type {
|
||||
ChatMessage,
|
||||
|
|
@ -129,7 +129,7 @@ export function slashCommandFromPromptFile(
|
|||
messages,
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
yield stripImages(chunk.content);
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
|
||||
context.llm.systemMessage = originalSystemMessage;
|
||||
|
|
@ -236,7 +236,8 @@ function updateChatHistory(
|
|||
const messages = [...history];
|
||||
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const { role, content } = messages[i];
|
||||
const message = messages[i];
|
||||
const { role, content } = message;
|
||||
if (role !== "user") {
|
||||
continue;
|
||||
}
|
||||
|
|
@ -254,7 +255,7 @@ function updateChatHistory(
|
|||
typeof content === "string" &&
|
||||
content.startsWith(`/${commandName}`)
|
||||
) {
|
||||
messages[i] = { ...messages[i], content: renderedPrompt };
|
||||
messages[i] = { ...message, content: renderedPrompt };
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
157
core/context/mcp/index.ts
Normal file
157
core/context/mcp/index.ts
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
|
||||
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
|
||||
import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../..";
|
||||
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
|
||||
import MCPContextProvider from "../providers/MCPContextProvider";
|
||||
|
||||
class MCPConnectionSingleton {
|
||||
private static instance: MCPConnectionSingleton;
|
||||
public client: Client;
|
||||
private transport: Transport;
|
||||
|
||||
private constructor(private readonly options: MCPOptions) {
|
||||
this.transport = this.constructTransport(options);
|
||||
|
||||
this.client = new Client(
|
||||
{
|
||||
name: "continue-client",
|
||||
version: "1.0.0",
|
||||
},
|
||||
{
|
||||
capabilities: {},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
public static getInstance(options: MCPOptions): MCPConnectionSingleton {
|
||||
if (!MCPConnectionSingleton.instance) {
|
||||
MCPConnectionSingleton.instance = new MCPConnectionSingleton(options);
|
||||
}
|
||||
return MCPConnectionSingleton.instance;
|
||||
}
|
||||
|
||||
public static getExistingInstance(): MCPConnectionSingleton | null {
|
||||
return MCPConnectionSingleton.instance;
|
||||
}
|
||||
|
||||
private constructTransport(options: MCPOptions): Transport {
|
||||
switch (options.transport.type) {
|
||||
case "stdio":
|
||||
return new StdioClientTransport({
|
||||
command: options.transport.command,
|
||||
args: options.transport.args,
|
||||
});
|
||||
case "websocket":
|
||||
return new WebSocketClientTransport(new URL(options.transport.url));
|
||||
case "sse":
|
||||
return new SSEClientTransport(new URL(options.transport.url));
|
||||
default:
|
||||
throw new Error(
|
||||
`Unsupported transport type: ${(options.transport as any).type}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private isConnected: boolean = false;
|
||||
private connectPromise: Promise<void> | null = null;
|
||||
|
||||
private async connectClient() {
|
||||
if (this.isConnected) {
|
||||
// Already connected
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.connectPromise) {
|
||||
// Connection is already in progress; wait for it to complete
|
||||
await this.connectPromise;
|
||||
return;
|
||||
}
|
||||
|
||||
this.connectPromise = (async () => {
|
||||
await this.client.connect(this.transport);
|
||||
this.isConnected = true;
|
||||
})();
|
||||
|
||||
try {
|
||||
await this.connectPromise;
|
||||
} catch (error) {
|
||||
// Handle connection error if needed
|
||||
throw error;
|
||||
} finally {
|
||||
// Reset the promise so future attempts can try again if necessary
|
||||
this.connectPromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
async modifyConfig(config: ContinueConfig): Promise<ContinueConfig> {
|
||||
try {
|
||||
await this.connectClient();
|
||||
} catch (error: any) {
|
||||
if (!error.message.startsWith("StdioClientTransport already started")) {
|
||||
console.error("Failed to connect client:", error);
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
||||
// Resources <—> Context Provider
|
||||
const { resources } = await this.client.listResources();
|
||||
|
||||
const submenuItems = resources.map((resource: any) => ({
|
||||
title: resource.name,
|
||||
description: resource.description,
|
||||
id: resource.uri,
|
||||
}));
|
||||
|
||||
if (!config.contextProviders) {
|
||||
config.contextProviders = [];
|
||||
}
|
||||
|
||||
config.contextProviders!.push(
|
||||
new MCPContextProvider({
|
||||
submenuItems,
|
||||
client: this.client,
|
||||
}),
|
||||
);
|
||||
|
||||
// Tools <—> Tools
|
||||
const { tools } = await this.client.listTools();
|
||||
const continueTools: Tool[] = tools.map((tool) => ({
|
||||
displayTitle: tool.name,
|
||||
function: {
|
||||
description: tool.description,
|
||||
name: tool.name,
|
||||
parameters: tool.inputSchema,
|
||||
},
|
||||
readonly: false,
|
||||
type: "function",
|
||||
wouldLikeTo: `use the ${tool.name} tool`,
|
||||
uri: `mcp://${tool.name}`,
|
||||
}));
|
||||
|
||||
config.tools = [...config.tools, ...continueTools];
|
||||
|
||||
// Prompts <—> Slash commands
|
||||
const { prompts } = await this.client.listPrompts();
|
||||
if (!config.slashCommands) {
|
||||
config.slashCommands = [];
|
||||
}
|
||||
|
||||
const slashCommands: SlashCommand[] = prompts.map((prompt) => {
|
||||
return constructMcpSlashCommand(
|
||||
this.client,
|
||||
prompt.name,
|
||||
prompt.description,
|
||||
prompt.arguments?.map((a) => a.name),
|
||||
);
|
||||
});
|
||||
config.slashCommands!.push(...slashCommands);
|
||||
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
||||
export default MCPConnectionSingleton;
|
||||
66
core/context/providers/MCPContextProvider.ts
Normal file
66
core/context/providers/MCPContextProvider.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
|
||||
import { BaseContextProvider } from "../";
|
||||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../";
|
||||
|
||||
interface MCPContextProviderOptions {
|
||||
submenuItems: ContextSubmenuItem[];
|
||||
client: Client;
|
||||
}
|
||||
|
||||
class MCPContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "mcp",
|
||||
displayTitle: "MCP",
|
||||
description: "Model Context Protocol",
|
||||
type: "submenu",
|
||||
};
|
||||
|
||||
constructor(options: MCPContextProviderOptions) {
|
||||
super(options);
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const { contents } = await (
|
||||
this.options as MCPContextProviderOptions
|
||||
).client.readResource({ uri: query });
|
||||
|
||||
return await Promise.all(
|
||||
contents.map(async (resource) => {
|
||||
const content = resource.text;
|
||||
if (typeof content !== "string") {
|
||||
throw new Error(
|
||||
"Continue currently only supports text resources from MCP",
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
name: resource.uri,
|
||||
description: resource.uri,
|
||||
content,
|
||||
uri: {
|
||||
type: "url",
|
||||
value: resource.uri,
|
||||
},
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
return (this.options as MCPContextProviderOptions).submenuItems;
|
||||
}
|
||||
}
|
||||
|
||||
export default MCPContextProvider;
|
||||
|
|
@ -3,12 +3,37 @@ import {
|
|||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
FetchFunction,
|
||||
} from "../..";
|
||||
import { getHeaders } from "../../continueServer/stubs/headers";
|
||||
import { TRIAL_PROXY_URL } from "../../control-plane/client";
|
||||
|
||||
export const fetchSearchResults = async (
|
||||
query: string,
|
||||
n: number,
|
||||
fetchFn: FetchFunction,
|
||||
): Promise<ContextItem[]> => {
|
||||
const resp = await fetchFn(WebContextProvider.ENDPOINT, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(await getHeaders()),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query,
|
||||
n,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
const text = await resp.text();
|
||||
throw new Error(`Failed to fetch web context: ${text}`);
|
||||
}
|
||||
return await resp.json();
|
||||
};
|
||||
|
||||
export default class WebContextProvider extends BaseContextProvider {
|
||||
private static ENDPOINT = new URL("web", TRIAL_PROXY_URL);
|
||||
public static ENDPOINT = new URL("web", TRIAL_PROXY_URL);
|
||||
private static DEFAULT_N = 6;
|
||||
|
||||
static description: ContextProviderDescription = {
|
||||
|
|
@ -23,22 +48,10 @@ export default class WebContextProvider extends BaseContextProvider {
|
|||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const resp = await extras.fetch(WebContextProvider.ENDPOINT, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(await getHeaders()),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query: extras.fullInput,
|
||||
n: this.options.n ?? WebContextProvider.DEFAULT_N,
|
||||
}),
|
||||
});
|
||||
if (!resp.ok) {
|
||||
const text = await resp.text();
|
||||
throw new Error(`Failed to fetch web context: ${text}`);
|
||||
}
|
||||
const json = await resp.json();
|
||||
return json;
|
||||
return await fetchSearchResults(
|
||||
extras.fullInput,
|
||||
this.options.n ?? WebContextProvider.DEFAULT_N,
|
||||
extras.fetch,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import GoogleContextProvider from "./GoogleContextProvider";
|
|||
import GreptileContextProvider from "./GreptileContextProvider";
|
||||
import HttpContextProvider from "./HttpContextProvider";
|
||||
import JiraIssuesContextProvider from "./JiraIssuesContextProvider/";
|
||||
import MCPContextProvider from "./MCPContextProvider";
|
||||
import OpenFilesContextProvider from "./OpenFilesContextProvider";
|
||||
import OSContextProvider from "./OSContextProvider";
|
||||
import PostgresContextProvider from "./PostgresContextProvider";
|
||||
|
|
@ -60,6 +61,7 @@ export const Providers: (typeof BaseContextProvider)[] = [
|
|||
DiscordContextProvider,
|
||||
GreptileContextProvider,
|
||||
WebContextProvider,
|
||||
MCPContextProvider,
|
||||
];
|
||||
|
||||
export function contextProviderClassFromName(
|
||||
|
|
|
|||
|
|
@ -4,4 +4,5 @@ export const INSTRUCTIONS_BASE_ITEM: ContextItem = {
|
|||
name: "Instructions",
|
||||
description: "Instructions",
|
||||
content: "",
|
||||
hidden: true,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { Chunk, ContinueConfig, IDE, ILLM } from "../..";
|
||||
import { getModelByRole } from "../../config/util";
|
||||
import { stripImages } from "../../llm/images";
|
||||
import generateRepoMap from "../../util/generateRepoMap";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
|
||||
const SUPPORTED_MODEL_TITLE_FAMILIES = [
|
||||
"claude-3",
|
||||
|
|
@ -58,11 +58,14 @@ After this, your response should begin with a <results> tag, followed by a list
|
|||
|
||||
This is the question that you should select relevant files for: "${input}"`;
|
||||
|
||||
const response = await llm.chat([
|
||||
{ role: "user", content: prompt },
|
||||
{ role: "assistant", content: "<reasoning>" },
|
||||
], new AbortController().signal);
|
||||
const content = stripImages(response.content);
|
||||
const response = await llm.chat(
|
||||
[
|
||||
{ role: "user", content: prompt },
|
||||
{ role: "assistant", content: "<reasoning>" },
|
||||
],
|
||||
new AbortController().signal,
|
||||
);
|
||||
const content = renderChatMessage(response);
|
||||
console.debug("Repo map retrieval response: ", content);
|
||||
|
||||
if (!content.includes("\n")) {
|
||||
|
|
|
|||
51
core/core.ts
51
core/core.ts
|
|
@ -36,6 +36,7 @@ import { TTS } from "./util/tts";
|
|||
|
||||
import type { ContextItemId, IDE, IndexingProgressUpdate } from ".";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import { callTool } from "./tools/callTool";
|
||||
import type { IMessenger, Message } from "./util/messenger";
|
||||
|
||||
export class Core {
|
||||
|
|
@ -154,10 +155,10 @@ export class Core {
|
|||
// Index on initialization
|
||||
void this.ide.getWorkspaceDirs().then(async (dirs) => {
|
||||
// Respect pauseCodebaseIndexOnStart user settings
|
||||
this.indexingPauseToken.paused = true;
|
||||
if (ideSettings.pauseCodebaseIndexOnStart) {
|
||||
this.indexingPauseToken.paused = true;
|
||||
void this.messenger.request("indexProgress", {
|
||||
progress: 1,
|
||||
progress: 0,
|
||||
desc: "Initial Indexing Skipped",
|
||||
status: "paused",
|
||||
});
|
||||
|
|
@ -382,6 +383,7 @@ export class Core {
|
|||
}
|
||||
|
||||
const model = await configHandler.llmFromTitle(msg.data.title);
|
||||
|
||||
const gen = model.streamChat(
|
||||
msg.data.messages,
|
||||
new AbortController().signal,
|
||||
|
|
@ -402,8 +404,11 @@ export class Core {
|
|||
});
|
||||
break;
|
||||
}
|
||||
|
||||
const chunk = next.value;
|
||||
|
||||
// @ts-ignore
|
||||
yield { content: next.value.content };
|
||||
yield { content: chunk };
|
||||
next = await gen.next();
|
||||
}
|
||||
|
||||
|
|
@ -770,10 +775,44 @@ export class Core {
|
|||
const ignoreInstance = ignore().add(defaultIgnoreFile);
|
||||
let rootDirectory = await this.ide.getWorkspaceDirs();
|
||||
const relativeFilePath = path.relative(rootDirectory[0], filepath);
|
||||
if (!ignoreInstance.ignores(relativeFilePath)) {
|
||||
recentlyEditedFilesCache.set(filepath, filepath);
|
||||
try {
|
||||
if (!ignoreInstance.ignores(relativeFilePath)) {
|
||||
recentlyEditedFilesCache.set(filepath, filepath);
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof RangeError) {
|
||||
// do nothing, this can happen when editing a file outside the workspace such as `../extensions/.continue-debug/config.json`
|
||||
} else {
|
||||
console.debug("unhandled ignores error", relativeFilePath, e);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
on("tools/call", async ({ data: { toolCall } }) => {
|
||||
const config = await this.configHandler.loadConfig();
|
||||
const tool = config.tools.find(
|
||||
(t) => t.function.name === toolCall.function.name,
|
||||
);
|
||||
|
||||
if (!tool) {
|
||||
throw new Error(`Tool ${toolCall.function.name} not found`);
|
||||
}
|
||||
|
||||
const llm = await this.getSelectedModel();
|
||||
|
||||
const contextItems = await callTool(
|
||||
tool.uri ?? tool.function.name,
|
||||
JSON.parse(toolCall.function.arguments || "{}"),
|
||||
{
|
||||
ide: this.ide,
|
||||
llm,
|
||||
fetch: (url, init) =>
|
||||
fetchwithRequestOptions(url, init, config.requestOptions),
|
||||
},
|
||||
);
|
||||
|
||||
return { contextItems };
|
||||
});
|
||||
}
|
||||
|
||||
private indexingCancellationController: AbortController | undefined;
|
||||
|
|
@ -803,6 +842,8 @@ export class Core {
|
|||
this.indexingCancellationController.signal,
|
||||
)) {
|
||||
let updateToSend = { ...update };
|
||||
// TODO reconsider this status overwrite?
|
||||
// original goal was to not concern users with edge noncritical errors
|
||||
if (update.status === "failed") {
|
||||
updateToSend.status = "done";
|
||||
updateToSend.desc = "Indexing complete";
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { distance } from "fastest-levenshtein";
|
||||
|
||||
import { ChatMessage } from "../index.js";
|
||||
import { stripImages } from "../llm/images.js";
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
|
||||
export type LineStream = AsyncGenerator<string>;
|
||||
|
||||
|
|
@ -103,7 +103,7 @@ export async function* streamLines(
|
|||
try {
|
||||
for await (const update of streamCompletion) {
|
||||
const chunk =
|
||||
typeof update === "string" ? update : stripImages(update.content);
|
||||
typeof update === "string" ? update : renderChatMessage(update);
|
||||
buffer += chunk;
|
||||
const lines = buffer.split("\n");
|
||||
buffer = lines.pop() ?? "";
|
||||
|
|
|
|||
148
core/index.d.ts
vendored
148
core/index.d.ts
vendored
|
|
@ -42,11 +42,18 @@ export interface IndexingProgressUpdate {
|
|||
progress: number;
|
||||
desc: string;
|
||||
shouldClearIndexes?: boolean;
|
||||
status: "loading" | "indexing" | "done" | "failed" | "paused" | "disabled";
|
||||
status:
|
||||
| "loading"
|
||||
| "indexing"
|
||||
| "done"
|
||||
| "failed"
|
||||
| "paused"
|
||||
| "disabled"
|
||||
| "cancelled";
|
||||
debugInfo?: string;
|
||||
}
|
||||
|
||||
// This is more or less a V2 of IndexingProgressUpdate
|
||||
// This is more or less a V2 of IndexingProgressUpdate for docs etc.
|
||||
export interface IndexingStatus {
|
||||
id: string;
|
||||
type: "docs";
|
||||
|
|
@ -240,7 +247,6 @@ export interface Session {
|
|||
title: string;
|
||||
workspaceDirectory: string;
|
||||
history: ChatHistoryItem[];
|
||||
checkpoints?: Checkpoint[];
|
||||
}
|
||||
|
||||
export interface SessionMetadata {
|
||||
|
|
@ -288,7 +294,7 @@ export interface CompletionOptions extends BaseCompletionOptions {
|
|||
model: string;
|
||||
}
|
||||
|
||||
export type ChatMessageRole = "user" | "assistant" | "system";
|
||||
export type ChatMessageRole = "user" | "assistant" | "system" | "tool";
|
||||
|
||||
export interface MessagePart {
|
||||
type: "text" | "imageUrl";
|
||||
|
|
@ -298,11 +304,52 @@ export interface MessagePart {
|
|||
|
||||
export type MessageContent = string | MessagePart[];
|
||||
|
||||
export interface ChatMessage {
|
||||
role: ChatMessageRole;
|
||||
export interface ToolCall {
|
||||
id: string;
|
||||
type: "function";
|
||||
function: {
|
||||
name: string;
|
||||
arguments: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ToolCallDelta {
|
||||
id?: string;
|
||||
type?: "function";
|
||||
function?: {
|
||||
name?: string;
|
||||
arguments?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ToolResultChatMessage {
|
||||
role: "tool";
|
||||
content: string;
|
||||
toolCallId: string;
|
||||
}
|
||||
|
||||
export interface UserChatMessage {
|
||||
role: "user";
|
||||
content: MessageContent;
|
||||
}
|
||||
|
||||
export interface AssistantChatMessage {
|
||||
role: "assistant";
|
||||
content: MessageContent;
|
||||
toolCalls?: ToolCallDelta[];
|
||||
}
|
||||
|
||||
export interface SystemChatMessage {
|
||||
role: "system";
|
||||
content: string;
|
||||
}
|
||||
|
||||
export type ChatMessage =
|
||||
| UserChatMessage
|
||||
| AssistantChatMessage
|
||||
| SystemChatMessage
|
||||
| ToolResultChatMessage;
|
||||
|
||||
export interface ContextItemId {
|
||||
providerTitle: string;
|
||||
itemId: string;
|
||||
|
|
@ -323,6 +370,7 @@ export interface ContextItem {
|
|||
editable?: boolean;
|
||||
icon?: string;
|
||||
uri?: ContextItemUri;
|
||||
hidden?: boolean;
|
||||
}
|
||||
|
||||
export interface ContextItemWithId extends ContextItem {
|
||||
|
|
@ -347,19 +395,39 @@ export interface PromptLog {
|
|||
prompt: string;
|
||||
completion: string;
|
||||
}
|
||||
export interface ChatHistoryItem {
|
||||
message: ChatMessage;
|
||||
editorState?: any;
|
||||
modifiers?: InputModifiers;
|
||||
contextItems: ContextItemWithId[];
|
||||
promptLogs?: PromptLog[];
|
||||
|
||||
type MessageModes = "chat" | "edit";
|
||||
|
||||
export type ToolStatus =
|
||||
| "generating"
|
||||
| "generated"
|
||||
| "calling"
|
||||
| "done"
|
||||
| "canceled";
|
||||
|
||||
// Will exist only on "assistant" messages with tool calls
|
||||
interface ToolCallState {
|
||||
toolCallId: string;
|
||||
toolCall: ToolCall;
|
||||
status: ToolStatus;
|
||||
parsedArgs: any;
|
||||
output?: ContextItem[];
|
||||
}
|
||||
|
||||
// LLM
|
||||
export interface ChatHistoryItem {
|
||||
message: ChatMessage;
|
||||
contextItems: ContextItemWithId[];
|
||||
editorState?: any;
|
||||
modifiers?: InputModifiers;
|
||||
promptLogs?: PromptLog[];
|
||||
toolCallState?: ToolCallState;
|
||||
isGatheringContext?: boolean;
|
||||
checkpoint?: Checkpoint;
|
||||
isBeforeCheckpoint?: boolean;
|
||||
}
|
||||
|
||||
export interface LLMFullCompletionOptions extends BaseCompletionOptions {
|
||||
log?: boolean;
|
||||
|
||||
model?: string;
|
||||
}
|
||||
|
||||
|
|
@ -700,7 +768,8 @@ type ModelProvider =
|
|||
| "nebius"
|
||||
| "xAI"
|
||||
| "moonshot"
|
||||
| "siliconflow";
|
||||
| "siliconflow"
|
||||
| "function-network";
|
||||
|
||||
export type ModelName =
|
||||
| "AUTODETECT"
|
||||
|
|
@ -855,6 +924,27 @@ interface Prediction {
|
|||
}[];
|
||||
}
|
||||
|
||||
export interface ToolExtras {
|
||||
ide: IDE;
|
||||
llm: ILLM;
|
||||
fetch: FetchFunction;
|
||||
}
|
||||
|
||||
export interface Tool {
|
||||
type: "function";
|
||||
function: {
|
||||
name: string;
|
||||
description?: string;
|
||||
parameters?: Record<string, any>;
|
||||
strict?: boolean | null;
|
||||
};
|
||||
|
||||
displayTitle: string;
|
||||
wouldLikeTo: string;
|
||||
readonly: boolean;
|
||||
uri?: string;
|
||||
}
|
||||
|
||||
interface BaseCompletionOptions {
|
||||
temperature?: number;
|
||||
topP?: number;
|
||||
|
|
@ -871,6 +961,7 @@ interface BaseCompletionOptions {
|
|||
raw?: boolean;
|
||||
stream?: boolean;
|
||||
prediction?: Prediction;
|
||||
tools?: Tool[];
|
||||
}
|
||||
|
||||
export interface ModelCapability {
|
||||
|
|
@ -913,6 +1004,7 @@ export type EmbeddingsProviderName =
|
|||
| "nebius"
|
||||
| "vertexai"
|
||||
| "watsonx"
|
||||
| "function-network"
|
||||
| "siliconflow";
|
||||
|
||||
export interface EmbedOptions {
|
||||
|
|
@ -984,6 +1076,28 @@ export interface TabAutocompleteOptions {
|
|||
showWhateverWeHaveAtXMs?: number;
|
||||
}
|
||||
|
||||
interface StdioOptions {
|
||||
type: "stdio";
|
||||
command: string;
|
||||
args: string[];
|
||||
}
|
||||
|
||||
interface WebSocketOptions {
|
||||
type: "websocket";
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface SSEOptions {
|
||||
type: "sse";
|
||||
url: string;
|
||||
}
|
||||
|
||||
type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions;
|
||||
|
||||
export interface MCPOptions {
|
||||
transport: TransportOptions;
|
||||
}
|
||||
|
||||
export interface ContinueUIConfig {
|
||||
codeBlockToolbarPosition?: "top" | "bottom";
|
||||
fontSize?: number;
|
||||
|
|
@ -1089,6 +1203,8 @@ interface ExperimentalConfig {
|
|||
* This is needed to crawl a large number of documentation sites that are dynamically rendered.
|
||||
*/
|
||||
useChromiumForDocsCrawling?: boolean;
|
||||
useTools?: boolean;
|
||||
modelContextProtocolServer?: MCPOptions;
|
||||
}
|
||||
|
||||
interface AnalyticsConfig {
|
||||
|
|
@ -1193,6 +1309,7 @@ export interface ContinueConfig {
|
|||
experimental?: ExperimentalConfig;
|
||||
analytics?: AnalyticsConfig;
|
||||
docs?: SiteIndexingConfig[];
|
||||
tools: Tool[];
|
||||
}
|
||||
|
||||
export interface BrowserSerializedContinueConfig {
|
||||
|
|
@ -1212,6 +1329,7 @@ export interface BrowserSerializedContinueConfig {
|
|||
experimental?: ExperimentalConfig;
|
||||
analytics?: AnalyticsConfig;
|
||||
docs?: SiteIndexingConfig[];
|
||||
tools: Tool[];
|
||||
}
|
||||
|
||||
// DOCS SUGGESTIONS AND PACKAGE INFO
|
||||
|
|
|
|||
|
|
@ -145,9 +145,7 @@ export class CodebaseIndexer {
|
|||
}
|
||||
}
|
||||
|
||||
async *refreshFiles(
|
||||
files: string[],
|
||||
): AsyncGenerator<IndexingProgressUpdate> {
|
||||
async *refreshFiles(files: string[]): AsyncGenerator<IndexingProgressUpdate> {
|
||||
let progress = 0;
|
||||
if (files.length === 0) {
|
||||
yield {
|
||||
|
|
@ -192,9 +190,9 @@ export class CodebaseIndexer {
|
|||
|
||||
if (dirs.length === 0) {
|
||||
yield {
|
||||
progress,
|
||||
progress: 1,
|
||||
desc: "Nothing to index",
|
||||
status: "disabled",
|
||||
status: "done",
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
|
@ -238,9 +236,9 @@ export class CodebaseIndexer {
|
|||
directoryFiles.push(p);
|
||||
if (abortSignal.aborted) {
|
||||
yield {
|
||||
progress: 1,
|
||||
progress: 0,
|
||||
desc: "Indexing cancelled",
|
||||
status: "disabled",
|
||||
status: "cancelled",
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
|
@ -263,9 +261,9 @@ export class CodebaseIndexer {
|
|||
// Handle pausing in this loop because it's the only one really taking time
|
||||
if (abortSignal.aborted) {
|
||||
yield {
|
||||
progress: 1,
|
||||
progress: 0,
|
||||
desc: "Indexing cancelled",
|
||||
status: "disabled",
|
||||
status: "cancelled",
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,69 @@
|
|||
import { Response } from "node-fetch";
|
||||
|
||||
import { EmbeddingsProviderName, EmbedOptions } from "../../index.js";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
|
||||
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
|
||||
class FunctionNetworkEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "function-network";
|
||||
static maxBatchSize = 128;
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "https://api.function.network/v1/",
|
||||
model: "baai/bge-base-en-v1.5",
|
||||
};
|
||||
|
||||
private _getEndpoint() {
|
||||
if (!this.options.apiBase) {
|
||||
throw new Error(
|
||||
"No API base URL provided. Please set the 'apiBase' option in config.json",
|
||||
);
|
||||
}
|
||||
|
||||
this.options.apiBase = this.options.apiBase.endsWith("/")
|
||||
? this.options.apiBase
|
||||
: `${this.options.apiBase}/`;
|
||||
return new URL("embeddings", this.options.apiBase);
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
const batchedChunks = this.getBatchedChunks(chunks);
|
||||
return (
|
||||
await Promise.all(
|
||||
batchedChunks.map(async (batch) => {
|
||||
if (batch.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const fetchWithBackoff = () =>
|
||||
withExponentialBackoff<Response>(() =>
|
||||
this.fetch(this._getEndpoint(), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
input: batch,
|
||||
model: this.options.model,
|
||||
}),
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.options.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const resp = await fetchWithBackoff();
|
||||
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as any;
|
||||
return data.data.map(
|
||||
(result: { embedding: number[] }) => result.embedding,
|
||||
);
|
||||
}),
|
||||
)
|
||||
).flat();
|
||||
}
|
||||
}
|
||||
|
||||
export default FunctionNetworkEmbeddingsProvider;
|
||||
|
|
@ -6,6 +6,7 @@ import CohereEmbeddingsProvider from "./CohereEmbeddingsProvider.js";
|
|||
import ContinueProxyEmbeddingsProvider from "./ContinueProxyEmbeddingsProvider.js";
|
||||
import DeepInfraEmbeddingsProvider from "./DeepInfraEmbeddingsProvider.js";
|
||||
import FreeTrialEmbeddingsProvider from "./FreeTrialEmbeddingsProvider.js";
|
||||
import FunctionNetworkEmbeddingsProvider from "./FunctionNetworkEmbeddingsProvider.js";
|
||||
import GeminiEmbeddingsProvider from "./GeminiEmbeddingsProvider.js";
|
||||
import HuggingFaceTEIEmbeddingsProvider from "./HuggingFaceTEIEmbeddingsProvider.js";
|
||||
import LMStudioEmbeddingsProvider from "./LMStudio.js";
|
||||
|
|
@ -36,6 +37,7 @@ export const allEmbeddingsProviders: Record<
|
|||
openai: OpenAIEmbeddingsProvider,
|
||||
cohere: CohereEmbeddingsProvider,
|
||||
"free-trial": FreeTrialEmbeddingsProvider,
|
||||
"function-network": FunctionNetworkEmbeddingsProvider,
|
||||
"huggingface-tei": HuggingFaceTEIEmbeddingsProvider,
|
||||
gemini: GeminiEmbeddingsProvider,
|
||||
"continue-proxy": ContinueProxyEmbeddingsProvider,
|
||||
|
|
|
|||
|
|
@ -84,6 +84,13 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
|
|||
"llama3.2",
|
||||
];
|
||||
|
||||
function modelSupportsTools(modelName: string) {
|
||||
return (
|
||||
modelName.includes("claude") &&
|
||||
(modelName.includes("3-5") || modelName.includes("3.5"))
|
||||
);
|
||||
}
|
||||
|
||||
function modelSupportsImages(
|
||||
provider: ModelProvider,
|
||||
model: string,
|
||||
|
|
@ -124,6 +131,7 @@ const PARALLEL_PROVIDERS: ModelProvider[] = [
|
|||
"sambanova",
|
||||
"nebius",
|
||||
"vertexai",
|
||||
"function-network",
|
||||
];
|
||||
|
||||
function llmCanGenerateInParallel(
|
||||
|
|
@ -150,13 +158,12 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
|
|||
lower.includes("chat-bison") ||
|
||||
lower.includes("pplx") ||
|
||||
lower.includes("gemini") ||
|
||||
lower.includes("grok")||
|
||||
lower.includes("grok") ||
|
||||
lower.includes("moonshot")
|
||||
) {
|
||||
return undefined;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (lower.includes("llama3")) {
|
||||
if (lower.includes("llama3") || lower.includes("llama-3")) {
|
||||
return "llama3";
|
||||
}
|
||||
|
||||
|
|
@ -354,4 +361,5 @@ export {
|
|||
autodetectTemplateType,
|
||||
llmCanGenerateInParallel,
|
||||
modelSupportsImages,
|
||||
modelSupportsTools,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
import { ChatHistoryItem, ChatMessage, MessagePart } from "../index.js";
|
||||
import { normalizeToMessageParts } from "../util/messageContent.js";
|
||||
import { modelSupportsTools } from "./autodetect.js";
|
||||
|
||||
const SYSTEM_MESSAGE = `When generating new code:
|
||||
|
||||
|
|
@ -58,52 +60,67 @@ function helloWorld() {
|
|||
|
||||
Always follow these guidelines when generating code responses.`;
|
||||
|
||||
function hasCodeBlockWithFilename(content: ChatMessage["content"]): boolean {
|
||||
const contentStr = typeof content === "string" ? content : content[0].text;
|
||||
const TOOL_USE_RULES = `When using tools, follow the following guidelines:
|
||||
- Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.`;
|
||||
|
||||
if (!contentStr) {
|
||||
return false;
|
||||
function constructSystemPrompt(model: string): string | null {
|
||||
if (model.includes("sonnet")) {
|
||||
return SYSTEM_MESSAGE + "\n\n" + TOOL_USE_RULES;
|
||||
}
|
||||
if (modelSupportsTools(model)) {
|
||||
return TOOL_USE_RULES;
|
||||
}
|
||||
|
||||
const codeBlockRegex = /```[\w\W]*?\.[\w\W]*/;
|
||||
return codeBlockRegex.test(contentStr);
|
||||
return null;
|
||||
}
|
||||
|
||||
const CANCELED_TOOL_CALL_MESSAGE =
|
||||
"This tool call was cancelled by the user. You should clarify next steps, as they don't wish for you to use this tool.";
|
||||
|
||||
export function constructMessages(
|
||||
history: ChatHistoryItem[],
|
||||
model: string,
|
||||
): ChatMessage[] {
|
||||
const msgs = [];
|
||||
const msgs: ChatMessage[] = [];
|
||||
|
||||
// Only using this system message with Sonnet right now
|
||||
if (
|
||||
// hasCodeBlockWithFilename(history[0].message.content) &&
|
||||
model.includes("sonnet")
|
||||
) {
|
||||
const systemMessage = constructSystemPrompt(model);
|
||||
if (systemMessage) {
|
||||
msgs.push({
|
||||
role: "system" as const,
|
||||
content: SYSTEM_MESSAGE,
|
||||
content: systemMessage,
|
||||
});
|
||||
}
|
||||
|
||||
for (let i = 0; i < history.length; i++) {
|
||||
const historyItem = history[i];
|
||||
|
||||
let content = Array.isArray(historyItem.message.content)
|
||||
? historyItem.message.content
|
||||
: [{ type: "text", text: historyItem.message.content } as MessagePart];
|
||||
if (historyItem.message.role === "user") {
|
||||
// Gather context items for user messages
|
||||
let content = normalizeToMessageParts(historyItem.message);
|
||||
|
||||
const ctxItems = historyItem.contextItems.map((ctxItem) => {
|
||||
return { type: "text", text: `${ctxItem.content}\n` } as MessagePart;
|
||||
});
|
||||
const ctxItems = historyItem.contextItems.map((ctxItem) => {
|
||||
return { type: "text", text: `${ctxItem.content}\n` } as MessagePart;
|
||||
});
|
||||
|
||||
content = [...ctxItems, ...content];
|
||||
|
||||
msgs.push({
|
||||
role: historyItem.message.role,
|
||||
content,
|
||||
});
|
||||
content = [...ctxItems, ...content];
|
||||
msgs.push({
|
||||
...historyItem.message,
|
||||
content,
|
||||
});
|
||||
} else if (historyItem.toolCallState?.status === "canceled") {
|
||||
// Canceled tool call
|
||||
msgs.push({
|
||||
...historyItem.message,
|
||||
content: CANCELED_TOOL_CALL_MESSAGE,
|
||||
});
|
||||
} else {
|
||||
msgs.push(historyItem.message);
|
||||
}
|
||||
}
|
||||
|
||||
return msgs;
|
||||
// Remove the "id" from all of the messages
|
||||
return msgs.map((msg) => {
|
||||
const { id, ...rest } = msg as any;
|
||||
return rest;
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
|
|||
|
||||
import { ChatMessage, MessageContent, MessagePart } from "../index.js";
|
||||
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
import {
|
||||
AsyncEncoder,
|
||||
GPTAsyncEncoder,
|
||||
|
|
@ -9,7 +10,6 @@ import {
|
|||
} from "./asyncEncoder.js";
|
||||
import { autodetectTemplateType } from "./autodetect.js";
|
||||
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js";
|
||||
import { stripImages } from "./images.js";
|
||||
import llamaTokenizer from "./llamaTokenizer.js";
|
||||
interface Encoding {
|
||||
encode: Tiktoken["encode"];
|
||||
|
|
@ -115,19 +115,28 @@ function countTokens(
|
|||
}
|
||||
}
|
||||
|
||||
function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
|
||||
function messageHasToolCalls(msg: ChatMessage): boolean {
|
||||
return msg.role === "assistant" && !!msg.toolCalls;
|
||||
}
|
||||
|
||||
export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
|
||||
const flattened: ChatMessage[] = [];
|
||||
|
||||
for (let i = 0; i < msgs.length; i++) {
|
||||
const msg = msgs[i];
|
||||
|
||||
if (
|
||||
flattened.length > 0 &&
|
||||
flattened[flattened.length - 1].role === msg.role
|
||||
flattened[flattened.length - 1].role === msg.role &&
|
||||
!messageHasToolCalls(msg) &&
|
||||
!messageHasToolCalls(flattened[flattened.length - 1])
|
||||
) {
|
||||
flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`;
|
||||
} else {
|
||||
flattened.push(msg);
|
||||
}
|
||||
}
|
||||
|
||||
return flattened;
|
||||
}
|
||||
|
||||
|
|
@ -222,11 +231,8 @@ function pruneRawPromptFromBottom(
|
|||
return pruneStringFromBottom(modelName, maxTokens, prompt);
|
||||
}
|
||||
|
||||
function summarize(message: MessageContent): string {
|
||||
if (Array.isArray(message)) {
|
||||
return `${stripImages(message).substring(0, 100)}...`;
|
||||
}
|
||||
return `${message.substring(0, 100)}...`;
|
||||
function summarize(message: ChatMessage): string {
|
||||
return `${renderChatMessage(message).substring(0, 100)}...`;
|
||||
}
|
||||
|
||||
function pruneChatHistory(
|
||||
|
|
@ -257,7 +263,7 @@ function pruneChatHistory(
|
|||
for (let i = 0; i < longerThanOneThird.length; i++) {
|
||||
// Prune line-by-line from the top
|
||||
const message = longerThanOneThird[i];
|
||||
const content = stripImages(message.content);
|
||||
const content = renderChatMessage(message);
|
||||
const deltaNeeded = totalTokens - contextLength;
|
||||
const delta = Math.min(deltaNeeded, distanceFromThird[i]);
|
||||
message.content = pruneStringFromTop(
|
||||
|
|
@ -273,8 +279,8 @@ function pruneChatHistory(
|
|||
while (totalTokens > contextLength && i < chatHistory.length - 5) {
|
||||
const message = chatHistory[0];
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
totalTokens += countTokens(summarize(message.content), modelName);
|
||||
message.content = summarize(message.content);
|
||||
totalTokens += countTokens(summarize(message), modelName);
|
||||
message.content = summarize(message);
|
||||
i++;
|
||||
}
|
||||
|
||||
|
|
@ -297,8 +303,8 @@ function pruneChatHistory(
|
|||
) {
|
||||
const message = chatHistory[i];
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
totalTokens += countTokens(summarize(message.content), modelName);
|
||||
message.content = summarize(message.content);
|
||||
totalTokens += countTokens(summarize(message), modelName);
|
||||
message.content = summarize(message);
|
||||
i++;
|
||||
}
|
||||
|
||||
|
|
@ -314,7 +320,7 @@ function pruneChatHistory(
|
|||
message.content = pruneRawPromptFromTop(
|
||||
modelName,
|
||||
contextLength,
|
||||
stripImages(message.content),
|
||||
renderChatMessage(message),
|
||||
tokensForCompletion,
|
||||
);
|
||||
totalTokens = contextLength;
|
||||
|
|
@ -344,6 +350,24 @@ function addSpaceToAnyEmptyMessages(messages: ChatMessage[]): ChatMessage[] {
|
|||
});
|
||||
}
|
||||
|
||||
function chatMessageIsEmpty(message: ChatMessage): boolean {
|
||||
switch (message.role) {
|
||||
case "system":
|
||||
case "user":
|
||||
return (
|
||||
typeof message.content === "string" && message.content.trim() === ""
|
||||
);
|
||||
case "assistant":
|
||||
return (
|
||||
typeof message.content === "string" &&
|
||||
message.content.trim() === "" &&
|
||||
!message.toolCalls
|
||||
);
|
||||
case "tool":
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function compileChatMessages(
|
||||
modelName: string,
|
||||
msgs: ChatMessage[] | undefined,
|
||||
|
|
@ -357,7 +381,7 @@ function compileChatMessages(
|
|||
let msgsCopy = msgs
|
||||
? msgs
|
||||
.map((msg) => ({ ...msg }))
|
||||
.filter((msg) => msg.content !== "" && msg.role !== "system")
|
||||
.filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system")
|
||||
: [];
|
||||
|
||||
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
|
||||
|
|
@ -376,7 +400,7 @@ function compileChatMessages(
|
|||
) {
|
||||
let content = "";
|
||||
if (msgs?.[0].role === "system") {
|
||||
content = stripImages(msgs?.[0].content);
|
||||
content = renderChatMessage(msgs?.[0]);
|
||||
}
|
||||
if (systemMessage && systemMessage.trim() !== "") {
|
||||
const shouldAddNewLines = content !== "";
|
||||
|
|
@ -411,7 +435,7 @@ function compileChatMessages(
|
|||
if (!supportsImages) {
|
||||
for (const msg of msgsCopy) {
|
||||
if ("content" in msg && Array.isArray(msg.content)) {
|
||||
const content = stripImages(msg.content);
|
||||
const content = renderChatMessage(msg);
|
||||
msg.content = content;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
104
core/llm/flattenMessages.test.ts
Normal file
104
core/llm/flattenMessages.test.ts
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import { ChatMessage } from "..";
|
||||
import { flattenMessages } from "./countTokens";
|
||||
|
||||
describe("flattenMessages", () => {
|
||||
it("should return an empty array when given an empty array", () => {
|
||||
expect(flattenMessages([])).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return the same array when there is only one message", () => {
|
||||
const messages: ChatMessage[] = [{ role: "user", content: "Hello" }];
|
||||
expect(flattenMessages(messages)).toEqual(messages);
|
||||
});
|
||||
|
||||
it("should return the same array when messages have different roles", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there!" },
|
||||
{ role: "user", content: "How are you?" },
|
||||
];
|
||||
expect(flattenMessages(messages)).toEqual(messages);
|
||||
});
|
||||
|
||||
it("should combine consecutive messages with the same role", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "user", content: "How are you?" },
|
||||
{ role: "assistant", content: "I am an AI assistant." },
|
||||
{ role: "assistant", content: "How can I help you?" },
|
||||
];
|
||||
const expected: ChatMessage[] = [
|
||||
{ role: "user", content: "Hello\n\nHow are you?" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: "I am an AI assistant.\n\nHow can I help you?",
|
||||
},
|
||||
];
|
||||
expect(flattenMessages(messages)).toEqual(expected);
|
||||
});
|
||||
|
||||
it("should handle messages with undefined or empty content", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "user", content: "" },
|
||||
{ role: "assistant", content: "" },
|
||||
{ role: "assistant", content: "Sure, I can help with that." },
|
||||
];
|
||||
const expected: ChatMessage[] = [
|
||||
{ role: "user", content: "Hello\n\n" },
|
||||
{ role: "assistant", content: "\n\nSure, I can help with that." },
|
||||
];
|
||||
expect(flattenMessages(messages)).toEqual(expected);
|
||||
});
|
||||
|
||||
it("should not combine non-consecutive messages with the same role", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "First message" },
|
||||
{ role: "assistant", content: "Reply to first message" },
|
||||
{ role: "user", content: "Second message" },
|
||||
];
|
||||
expect(flattenMessages(messages)).toEqual(messages);
|
||||
});
|
||||
|
||||
it("should handle a mix of message roles and contents correctly", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Message one" },
|
||||
{ role: "user", content: "Message two" },
|
||||
{ role: "assistant", content: "Reply one" },
|
||||
{ role: "user", content: "Message three" },
|
||||
{ role: "user", content: "Message four" },
|
||||
{ role: "assistant", content: "Reply two" },
|
||||
];
|
||||
const expected: ChatMessage[] = [
|
||||
{ role: "user", content: "Message one\n\nMessage two" },
|
||||
{ role: "assistant", content: "Reply one" },
|
||||
{ role: "user", content: "Message three\n\nMessage four" },
|
||||
{ role: "assistant", content: "Reply two" },
|
||||
];
|
||||
expect(flattenMessages(messages)).toEqual(expected);
|
||||
});
|
||||
|
||||
it("should not combine adjacent assistant messages when one of them is a tool call", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "What's the capital of France?" },
|
||||
{ role: "assistant", content: "Paris" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: " ",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "test",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "getCapital",
|
||||
arguments: JSON.stringify({
|
||||
country: "France",
|
||||
}),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
expect(flattenMessages(messages).length).toBe(3);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
import { MessageContent } from "../index.js";
|
||||
|
||||
export function stripImages(content: MessageContent): string {
|
||||
if (Array.isArray(content)) {
|
||||
return content
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => part.text)
|
||||
.join("\n");
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
|
@ -4,7 +4,6 @@ import Handlebars from "handlebars";
|
|||
import {
|
||||
CacheBehavior,
|
||||
ChatMessage,
|
||||
ChatMessageRole,
|
||||
CompletionOptions,
|
||||
ILLM,
|
||||
LLMFullCompletionOptions,
|
||||
|
|
@ -24,6 +23,7 @@ import mergeJson from "../util/merge.js";
|
|||
import { Telemetry } from "../util/posthog.js";
|
||||
import { withExponentialBackoff } from "../util/withExponentialBackoff.js";
|
||||
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
import {
|
||||
autodetectPromptTemplates,
|
||||
autodetectTemplateFunction,
|
||||
|
|
@ -41,7 +41,6 @@ import {
|
|||
countTokens,
|
||||
pruneRawPromptFromTop,
|
||||
} from "./countTokens.js";
|
||||
import { stripImages } from "./images.js";
|
||||
import CompletionOptionsForModels from "./templates/options.js";
|
||||
|
||||
export abstract class BaseLLM implements ILLM {
|
||||
|
|
@ -372,7 +371,8 @@ export abstract class BaseLLM implements ILLM {
|
|||
`HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`,
|
||||
);
|
||||
} else {
|
||||
if (e.name !== "AbortError") { // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here
|
||||
if (e.name !== "AbortError") {
|
||||
// Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here
|
||||
console.debug(
|
||||
`${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`,
|
||||
);
|
||||
|
|
@ -414,7 +414,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
let formatted = "";
|
||||
for (const msg of msgsCopy) {
|
||||
if ("content" in msg && Array.isArray(msg.content)) {
|
||||
const content = stripImages(msg.content);
|
||||
const content = renderChatMessage(msg);
|
||||
msg.content = content;
|
||||
}
|
||||
formatted += `<${msg.role}>\n${msg.content || ""}\n\n`;
|
||||
|
|
@ -533,7 +533,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
};
|
||||
}
|
||||
|
||||
async complete(_prompt: string, signal: AbortSignal, options: LLMFullCompletionOptions = {}) {
|
||||
async complete(
|
||||
_prompt: string,
|
||||
signal: AbortSignal,
|
||||
options: LLMFullCompletionOptions = {},
|
||||
) {
|
||||
const { completionOptions, log, raw } =
|
||||
this._parseCompletionOptions(options);
|
||||
|
||||
|
|
@ -568,12 +572,16 @@ export abstract class BaseLLM implements ILLM {
|
|||
return completion;
|
||||
}
|
||||
|
||||
async chat(messages: ChatMessage[], signal: AbortSignal, options: LLMFullCompletionOptions = {}) {
|
||||
async chat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: LLMFullCompletionOptions = {},
|
||||
) {
|
||||
let completion = "";
|
||||
for await (const chunk of this.streamChat(messages, signal, options)) {
|
||||
completion += chunk.content;
|
||||
}
|
||||
return { role: "assistant" as ChatMessageRole, content: completion };
|
||||
return { role: "assistant" as const, content: completion };
|
||||
}
|
||||
|
||||
async *streamChat(
|
||||
|
|
@ -668,7 +676,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
}
|
||||
}
|
||||
|
||||
protected async _complete(prompt: string, signal: AbortSignal, options: CompletionOptions) {
|
||||
protected async _complete(
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
) {
|
||||
let completion = "";
|
||||
for await (const chunk of this._streamComplete(prompt, signal, options)) {
|
||||
completion += chunk;
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import {
|
|||
LLMOptions,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { stripImages } from "../images.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
|
||||
|
|
@ -30,11 +30,79 @@ class Anthropic extends BaseLLM {
|
|||
model: options.model === "claude-2" ? "claude-2.1" : options.model,
|
||||
stop_sequences: options.stop?.filter((x) => x.trim() !== ""),
|
||||
stream: options.stream ?? true,
|
||||
tools: options.tools?.map((tool) => ({
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
input_schema: tool.function.parameters,
|
||||
})),
|
||||
};
|
||||
|
||||
return finalOptions;
|
||||
}
|
||||
|
||||
private convertMessage(message: ChatMessage, addCaching: boolean): any {
|
||||
if (message.role === "tool") {
|
||||
return {
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "tool_result",
|
||||
tool_use_id: message.toolCallId,
|
||||
content: renderChatMessage(message) || undefined,
|
||||
},
|
||||
],
|
||||
};
|
||||
} else if (message.role === "assistant" && message.toolCalls) {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: message.toolCalls.map((toolCall) => ({
|
||||
type: "tool_use",
|
||||
id: toolCall.id,
|
||||
name: toolCall.function?.name,
|
||||
input: JSON.parse(toolCall.function?.arguments || "{}"),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
var chatMessage = {
|
||||
role: message.role,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: message.content,
|
||||
...(addCaching ? { cache_control: { type: "ephemeral" } } : {}),
|
||||
},
|
||||
],
|
||||
};
|
||||
return chatMessage;
|
||||
}
|
||||
|
||||
return {
|
||||
role: message.role,
|
||||
content: message.content.map((part, contentIdx) => {
|
||||
if (part.type === "text") {
|
||||
const newpart = {
|
||||
...part,
|
||||
// If multiple text parts, only add cache_control to the last one
|
||||
...(addCaching && contentIdx == message.content.length - 1
|
||||
? { cache_control: { type: "ephemeral" } }
|
||||
: {}),
|
||||
};
|
||||
return newpart;
|
||||
}
|
||||
return {
|
||||
type: "image",
|
||||
source: {
|
||||
type: "base64",
|
||||
media_type: "image/jpeg",
|
||||
data: part.imageUrl?.url.split(",")[1],
|
||||
},
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
public convertMessages(msgs: ChatMessage[]): any[] {
|
||||
// should be public for use within VertexAI
|
||||
const filteredmessages = msgs.filter(
|
||||
|
|
@ -54,43 +122,8 @@ class Anthropic extends BaseLLM {
|
|||
this.cacheBehavior?.cacheConversation &&
|
||||
lastTwoUserMsgIndices.includes(filteredMsgIdx);
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
var chatMessage = {
|
||||
...message,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: message.content,
|
||||
...(addCaching ? { cache_control: { type: "ephemeral" } } : {}),
|
||||
},
|
||||
],
|
||||
};
|
||||
return chatMessage;
|
||||
}
|
||||
|
||||
return {
|
||||
...message,
|
||||
content: message.content.map((part, contentIdx) => {
|
||||
if (part.type === "text") {
|
||||
const newpart = {
|
||||
...part,
|
||||
// If multiple text parts, only add cache_control to the last one
|
||||
...(addCaching && contentIdx == message.content.length - 1
|
||||
? { cache_control: { type: "ephemeral" } }
|
||||
: {}),
|
||||
};
|
||||
return newpart;
|
||||
}
|
||||
return {
|
||||
type: "image",
|
||||
source: {
|
||||
type: "base64",
|
||||
media_type: "image/jpeg",
|
||||
data: part.imageUrl?.url.split(",")[1],
|
||||
},
|
||||
};
|
||||
}),
|
||||
};
|
||||
const chatMessage = this.convertMessage(message, !!addCaching);
|
||||
return chatMessage;
|
||||
});
|
||||
return messages;
|
||||
}
|
||||
|
|
@ -102,7 +135,7 @@ class Anthropic extends BaseLLM {
|
|||
): AsyncGenerator<string> {
|
||||
const messages = [{ role: "user" as const, content: prompt }];
|
||||
for await (const update of this._streamChat(messages, signal, options)) {
|
||||
yield stripImages(update.content);
|
||||
yield renderChatMessage(update);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -114,9 +147,10 @@ class Anthropic extends BaseLLM {
|
|||
const shouldCacheSystemMessage =
|
||||
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
|
||||
const systemMessage: string = stripImages(
|
||||
messages.filter((m) => m.role === "system")[0]?.content,
|
||||
messages.filter((m) => m.role === "system")[0]?.content ?? "",
|
||||
);
|
||||
|
||||
const msgs = this.convertMessages(messages);
|
||||
const response = await this.fetch(new URL("messages", this.apiBase), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
|
|
@ -130,7 +164,7 @@ class Anthropic extends BaseLLM {
|
|||
},
|
||||
body: JSON.stringify({
|
||||
...this.convertArgs(options),
|
||||
messages: this.convertMessages(messages),
|
||||
messages: msgs,
|
||||
system: shouldCacheSystemMessage
|
||||
? [
|
||||
{
|
||||
|
|
@ -141,21 +175,74 @@ class Anthropic extends BaseLLM {
|
|||
]
|
||||
: systemMessage,
|
||||
}),
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const json = await response.json();
|
||||
if (json.type === "error") {
|
||||
if (json.error?.type === "overloaded_error") {
|
||||
throw new Error(
|
||||
"The Anthropic API is currently overloaded. Please check their status page: https://status.anthropic.com/#past-incidents",
|
||||
);
|
||||
}
|
||||
throw new Error(json.message);
|
||||
}
|
||||
throw new Error(
|
||||
`Anthropic API sent back ${response.status}: ${JSON.stringify(json)}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (options.stream === false) {
|
||||
const data = await response.json();
|
||||
yield { role: "assistant", content: data.content[0].text };
|
||||
return;
|
||||
}
|
||||
|
||||
let lastToolUseId: string | undefined;
|
||||
let lastToolUseName: string | undefined;
|
||||
for await (const value of streamSse(response)) {
|
||||
if (value.type == "message_start") {
|
||||
console.log(value);
|
||||
}
|
||||
if (value.delta?.text) {
|
||||
yield { role: "assistant", content: value.delta.text };
|
||||
// https://docs.anthropic.com/en/api/messages-streaming#event-types
|
||||
switch (value.type) {
|
||||
case "content_block_start":
|
||||
if (value.content_block.type === "tool_use") {
|
||||
lastToolUseId = value.content_block.id;
|
||||
lastToolUseName = value.content_block.name;
|
||||
}
|
||||
break;
|
||||
case "content_block_delta":
|
||||
// https://docs.anthropic.com/en/api/messages-streaming#delta-types
|
||||
switch (value.delta.type) {
|
||||
case "text_delta":
|
||||
yield { role: "assistant", content: value.delta.text };
|
||||
break;
|
||||
case "input_json_delta":
|
||||
if (!lastToolUseId || !lastToolUseName) {
|
||||
throw new Error("No tool use found");
|
||||
}
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: lastToolUseId,
|
||||
type: "function",
|
||||
function: {
|
||||
name: lastToolUseName,
|
||||
arguments: value.delta.partial_json,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case "content_block_stop":
|
||||
lastToolUseId = undefined;
|
||||
lastToolUseName = undefined;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import {
|
|||
MessageContent,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { stripImages } from "../images.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
/**
|
||||
|
|
@ -47,7 +47,7 @@ class Bedrock extends BaseLLM {
|
|||
): AsyncGenerator<string> {
|
||||
const messages = [{ role: "user" as const, content: prompt }];
|
||||
for await (const update of this._streamChat(messages, signal, options)) {
|
||||
yield stripImages(update.content);
|
||||
yield renderChatMessage(update);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -91,7 +91,7 @@ class Bedrock extends BaseLLM {
|
|||
|
||||
const input = this._generateConverseInput(messages, options);
|
||||
const command = new ConverseStreamCommand(input);
|
||||
const response = await client.send(command, { abortSignal: signal});
|
||||
const response = await client.send(command, { abortSignal: signal });
|
||||
|
||||
if (response.stream) {
|
||||
for await (const chunk of response.stream) {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
|
||||
import { stripImages } from "../images.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
|
||||
|
|
@ -36,12 +36,15 @@ export default class Cloudflare extends BaseLLM {
|
|||
model: this.model,
|
||||
...this._convertArgs(options),
|
||||
}),
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
|
||||
for await (const value of streamSse(resp)) {
|
||||
if (value.choices?.[0]?.delta?.content) {
|
||||
yield value.choices[0].delta;
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: value.choices[0].delta,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -56,7 +59,7 @@ export default class Cloudflare extends BaseLLM {
|
|||
signal,
|
||||
options,
|
||||
)) {
|
||||
yield stripImages(chunk.content);
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import {
|
|||
LLMOptions,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { stripImages } from "../images.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamJSON } from "../stream.js";
|
||||
|
||||
|
|
@ -51,7 +51,7 @@ class Cohere extends BaseLLM {
|
|||
): AsyncGenerator<string> {
|
||||
const messages = [{ role: "user" as const, content: prompt }];
|
||||
for await (const update of this._streamChat(messages, signal, options)) {
|
||||
yield stripImages(update.content);
|
||||
yield renderChatMessage(update);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -75,7 +75,7 @@ class Cohere extends BaseLLM {
|
|||
chat_history: this._convertMessages(messages),
|
||||
preamble: this.systemMessage,
|
||||
}),
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
|
||||
if (options.stream === false) {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import {
|
|||
LLMOptions,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { stripImages } from "../images.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
interface IFlowiseApiOptions {
|
||||
|
|
@ -126,7 +126,7 @@ class Flowise extends BaseLLM {
|
|||
): AsyncGenerator<string> {
|
||||
const message: ChatMessage = { role: "user", content: prompt };
|
||||
for await (const chunk of this._streamChat([message], signal, options)) {
|
||||
yield stripImages(chunk.content);
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -141,7 +141,7 @@ class Flowise extends BaseLLM {
|
|||
method: "POST",
|
||||
headers: this._getHeaders(),
|
||||
body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }),
|
||||
signal
|
||||
signal,
|
||||
}).then((res) => res.json());
|
||||
|
||||
while (await socketInfo.hasNextToken()) {
|
||||
|
|
|
|||
|
|
@ -74,7 +74,7 @@ class FreeTrial extends BaseLLM {
|
|||
prompt,
|
||||
...args,
|
||||
}),
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
|
||||
let completion = "";
|
||||
|
|
@ -82,10 +82,18 @@ class FreeTrial extends BaseLLM {
|
|||
yield value;
|
||||
completion += value;
|
||||
}
|
||||
this._countTokens(completion, args.model, false);
|
||||
void this._countTokens(completion, args.model, false);
|
||||
}
|
||||
|
||||
protected _convertMessage(message: ChatMessage) {
|
||||
if (message.role === "tool") {
|
||||
return {
|
||||
role: "tool",
|
||||
content: message.content,
|
||||
tool_call_id: message.toolCallId,
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
return message;
|
||||
}
|
||||
|
|
@ -123,7 +131,7 @@ class FreeTrial extends BaseLLM {
|
|||
messages: messages.map(this._convertMessage),
|
||||
...args,
|
||||
}),
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
|
||||
let completion = "";
|
||||
|
|
@ -158,7 +166,7 @@ class FreeTrial extends BaseLLM {
|
|||
suffix,
|
||||
...args,
|
||||
}),
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
|
||||
let completion = "";
|
||||
|
|
|
|||
41
core/llm/llms/FunctionNetwork.ts
Normal file
41
core/llm/llms/FunctionNetwork.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { LLMOptions, ModelProvider } from "../../index.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class FunctionNetwork extends OpenAI {
|
||||
static providerName: ModelProvider = "function-network";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.function.network/v1/",
|
||||
model: "meta/llama-3.1-70b-instruct",
|
||||
};
|
||||
|
||||
private static modelConversion: { [key: string]: string } = {
|
||||
"mistral-7b": "mistral/mistral-7b-instruct-v0.1",
|
||||
"llama3-8b": "meta/llama-3-8b-instruct",
|
||||
"llama3.1-8b": "meta/llama-3.1-8b-instruct",
|
||||
"llama3.1-70b": "meta/llama-3.1-70b-instruct",
|
||||
"deepseek-7b": "thebloke/deepseek-coder-6.7b-instruct-awq",
|
||||
};
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
}
|
||||
|
||||
protected _convertModelName(model: string): string {
|
||||
return FunctionNetwork.modelConversion[model] ?? model;
|
||||
}
|
||||
|
||||
public supportsFim(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
public supportsCompletions(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
public supportsPrefill(): boolean {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export default FunctionNetwork;
|
||||
|
|
@ -5,7 +5,7 @@ import {
|
|||
MessagePart,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { stripImages } from "../images.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamResponse } from "../stream.js";
|
||||
|
||||
|
|
@ -19,7 +19,8 @@ class Gemini extends BaseLLM {
|
|||
};
|
||||
|
||||
// Function to convert completion options to Gemini format
|
||||
public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI
|
||||
public convertArgs(options: CompletionOptions) {
|
||||
// should be public for use within VertexAI
|
||||
const finalOptions: any = {}; // Initialize an empty object
|
||||
|
||||
// Map known options
|
||||
|
|
@ -54,17 +55,19 @@ class Gemini extends BaseLLM {
|
|||
signal,
|
||||
options,
|
||||
)) {
|
||||
yield stripImages(message.content);
|
||||
yield renderChatMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
public removeSystemMessage(messages: ChatMessage[]) { // should be public for use within VertexAI
|
||||
public removeSystemMessage(messages: ChatMessage[]) {
|
||||
// should be public for use within VertexAI
|
||||
const msgs = [...messages];
|
||||
|
||||
if (msgs[0]?.role === "system") {
|
||||
const sysMsg = msgs.shift()?.content;
|
||||
// @ts-ignore
|
||||
if (msgs[0]?.role === "user") {
|
||||
// @ts-ignore
|
||||
msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`;
|
||||
}
|
||||
}
|
||||
|
|
@ -143,6 +146,9 @@ class Gemini extends BaseLLM {
|
|||
if (msg.role === "system" && !isV1API) {
|
||||
return null; // Don't include system message in contents
|
||||
}
|
||||
if (msg.role === "tool") {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
role: msg.role === "assistant" ? "model" : "user",
|
||||
parts:
|
||||
|
|
@ -165,7 +171,7 @@ class Gemini extends BaseLLM {
|
|||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
|
||||
let buffer = "";
|
||||
|
|
@ -234,7 +240,7 @@ class Gemini extends BaseLLM {
|
|||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
const data = await response.json();
|
||||
yield { role: "assistant", content: data.candidates[0].content };
|
||||
|
|
|
|||
|
|
@ -4,13 +4,11 @@ import {
|
|||
LLMOptions,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { stripImages } from "../images.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamResponse } from "../stream.js";
|
||||
|
||||
interface OllamaChatMessage extends ChatMessage {
|
||||
images?: string[];
|
||||
}
|
||||
type OllamaChatMessage = ChatMessage & { images?: string[] };
|
||||
|
||||
// See https://github.com/ollama/ollama/blob/main/docs/modelfile.md for details on each parameter
|
||||
interface ModelFileParams {
|
||||
|
|
@ -195,6 +193,10 @@ class Ollama extends BaseLLM {
|
|||
}
|
||||
|
||||
private _convertMessage(message: ChatMessage) {
|
||||
if (message.role === "tool") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
return message;
|
||||
}
|
||||
|
|
@ -210,7 +212,7 @@ class Ollama extends BaseLLM {
|
|||
|
||||
return {
|
||||
role: message.role,
|
||||
content: stripImages(message.content),
|
||||
content: renderChatMessage(message),
|
||||
images,
|
||||
};
|
||||
}
|
||||
|
|
@ -221,7 +223,7 @@ class Ollama extends BaseLLM {
|
|||
): ChatOptions {
|
||||
return {
|
||||
model: this._getModel(),
|
||||
messages: messages.map(this._convertMessage),
|
||||
messages: messages.map(this._convertMessage).filter(Boolean) as any,
|
||||
options: this._getModelFileParams(options),
|
||||
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
|
||||
stream: options.stream,
|
||||
|
|
|
|||
|
|
@ -3,8 +3,9 @@ import {
|
|||
CompletionOptions,
|
||||
LLMOptions,
|
||||
ModelProvider,
|
||||
Tool,
|
||||
} from "../../index.js";
|
||||
import { stripImages } from "../images.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
|
||||
|
|
@ -56,6 +57,14 @@ class OpenAI extends BaseLLM {
|
|||
};
|
||||
|
||||
protected _convertMessage(message: ChatMessage) {
|
||||
if (message.role === "tool") {
|
||||
return {
|
||||
role: "tool",
|
||||
content: message.content,
|
||||
tool_call_id: message.toolCallId,
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
return message;
|
||||
} else if (!message.content.some((item) => item.type !== "text")) {
|
||||
|
|
@ -99,8 +108,22 @@ class OpenAI extends BaseLLM {
|
|||
return ["gpt-4o-mini", "gpt-4o"].includes(model);
|
||||
}
|
||||
|
||||
private convertTool(tool: Tool): any {
|
||||
return {
|
||||
type: tool.type,
|
||||
function: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
parameters: tool.function.parameters,
|
||||
strict: tool.function.strict,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) {
|
||||
const url = new URL(this.apiBase!);
|
||||
const tools = options.tools?.map(this.convertTool);
|
||||
|
||||
const finalOptions: any = {
|
||||
messages: messages.map(this._convertMessage),
|
||||
model: this._convertModelName(options.model),
|
||||
|
|
@ -122,6 +145,7 @@ class OpenAI extends BaseLLM {
|
|||
this.apiType === "azure"
|
||||
? options.stop?.slice(0, 4)
|
||||
: options.stop,
|
||||
tools,
|
||||
};
|
||||
|
||||
// OpenAI o1-preview and o1-mini:
|
||||
|
|
@ -206,7 +230,7 @@ class OpenAI extends BaseLLM {
|
|||
signal,
|
||||
options,
|
||||
)) {
|
||||
yield stripImages(chunk.content);
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -249,7 +273,7 @@ class OpenAI extends BaseLLM {
|
|||
options.raw)
|
||||
) {
|
||||
for await (const content of this._legacystreamComplete(
|
||||
stripImages(messages[messages.length - 1]?.content || ""),
|
||||
renderChatMessage(messages[messages.length - 1]),
|
||||
signal,
|
||||
options,
|
||||
)) {
|
||||
|
|
@ -266,6 +290,9 @@ class OpenAI extends BaseLLM {
|
|||
body.messages = body.messages.map((m: any) => ({
|
||||
...m,
|
||||
content: m.content === "" ? " " : m.content,
|
||||
// We call it toolCalls, they call it tool_calls
|
||||
tool_calls: m.toolCalls,
|
||||
tool_call_id: m.toolCallId,
|
||||
})) as any;
|
||||
const response = await this.fetch(this._getEndpoint("chat/completions"), {
|
||||
method: "POST",
|
||||
|
|
@ -283,7 +310,25 @@ class OpenAI extends BaseLLM {
|
|||
|
||||
for await (const value of streamSse(response)) {
|
||||
if (value.choices?.[0]?.delta?.content) {
|
||||
yield value.choices[0].delta;
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: value.choices[0].delta.content,
|
||||
};
|
||||
} else if (value.choices?.[0]?.delta?.tool_calls) {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: value.choices?.[0]?.delta?.tool_calls.map(
|
||||
(tool_call: any) => ({
|
||||
id: tool_call.id,
|
||||
type: tool_call.type,
|
||||
function: {
|
||||
name: tool_call.function.name,
|
||||
arguments: tool_call.function.arguments,
|
||||
},
|
||||
}),
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -333,4 +378,4 @@ class OpenAI extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
export default OpenAI;
|
||||
export default OpenAI;
|
||||
|
|
|
|||
|
|
@ -4,13 +4,11 @@ import {
|
|||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
MessagePart,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { stripImages } from "../images.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
import { streamResponse } from "../stream.js";
|
||||
import { streamResponse, streamSse } from "../stream.js";
|
||||
|
||||
import Anthropic from "./Anthropic.js";
|
||||
import Gemini from "./Gemini.js";
|
||||
|
|
@ -40,16 +38,17 @@ class VertexAI extends BaseLLM {
|
|||
super(_options);
|
||||
this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options);
|
||||
this.vertexProvider =
|
||||
_options.model.includes("mistral") || _options.model.includes("codestral") || _options.model.includes("mixtral")
|
||||
_options.model.includes("mistral") ||
|
||||
_options.model.includes("codestral") ||
|
||||
_options.model.includes("mixtral")
|
||||
? "mistral"
|
||||
: _options.model.includes("claude")
|
||||
? "anthropic"
|
||||
: _options.model.includes("gemini")
|
||||
? "gemini" :
|
||||
"unknown";
|
||||
? "gemini"
|
||||
: "unknown";
|
||||
this.anthropicInstance = new Anthropic(_options);
|
||||
this.geminiInstance = new Gemini(_options);
|
||||
|
||||
}
|
||||
|
||||
async fetch(url: RequestInfo | URL, init?: RequestInit) {
|
||||
|
|
@ -82,18 +81,18 @@ class VertexAI extends BaseLLM {
|
|||
};
|
||||
}
|
||||
|
||||
|
||||
protected async *StreamChatAnthropic(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
|
||||
const systemMessage: string = stripImages(
|
||||
messages.filter((m) => m.role === "system")[0]?.content,
|
||||
const shouldCacheSystemMessage =
|
||||
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
|
||||
const systemMessage: string = renderChatMessage(
|
||||
messages.filter((m) => m.role === "system")[0],
|
||||
);
|
||||
const apiURL = new URL(
|
||||
`publishers/anthropic/models/${options.model}:streamRawPredict`,
|
||||
this.apiBase
|
||||
this.apiBase,
|
||||
);
|
||||
|
||||
const response = await this.fetch(apiURL, {
|
||||
|
|
@ -108,12 +107,12 @@ class VertexAI extends BaseLLM {
|
|||
messages: this.anthropicInstance.convertMessages(messages),
|
||||
system: shouldCacheSystemMessage
|
||||
? [
|
||||
{
|
||||
type: "text",
|
||||
text: this.systemMessage,
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
]
|
||||
{
|
||||
type: "text",
|
||||
text: this.systemMessage,
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
]
|
||||
: systemMessage,
|
||||
}),
|
||||
});
|
||||
|
|
@ -125,14 +124,15 @@ class VertexAI extends BaseLLM {
|
|||
}
|
||||
|
||||
for await (const value of streamSse(response)) {
|
||||
if (value.type == "message_start") {console.log(value);}
|
||||
if (value.type == "message_start") {
|
||||
console.log(value);
|
||||
}
|
||||
if (value.delta?.text) {
|
||||
yield { role: "assistant", content: value.delta.text };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//Gemini
|
||||
|
||||
private async *streamChatGemini(
|
||||
|
|
@ -152,6 +152,10 @@ class VertexAI extends BaseLLM {
|
|||
if (msg.role === "system" && !isV1API) {
|
||||
return null; // Don't include system message in contents
|
||||
}
|
||||
if (msg.role === "tool") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
role: msg.role === "assistant" ? "model" : "user",
|
||||
parts:
|
||||
|
|
@ -168,8 +172,8 @@ class VertexAI extends BaseLLM {
|
|||
// if this.systemMessage is defined, reformat it for Gemini API
|
||||
...(this.systemMessage &&
|
||||
!isV1API && {
|
||||
systemInstruction: { parts: [{ text: this.systemMessage }] },
|
||||
}),
|
||||
systemInstruction: { parts: [{ text: this.systemMessage }] },
|
||||
}),
|
||||
};
|
||||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
|
|
@ -265,7 +269,6 @@ class VertexAI extends BaseLLM {
|
|||
|
||||
//Mistral
|
||||
|
||||
|
||||
protected async *StreamChatMistral(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions,
|
||||
|
|
@ -330,7 +333,7 @@ class VertexAI extends BaseLLM {
|
|||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
|
||||
for await (const chunk of streamSse(response)) {
|
||||
|
|
@ -338,8 +341,6 @@ class VertexAI extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//gecko
|
||||
protected async *streamFimGecko(
|
||||
prefix: string,
|
||||
|
|
@ -347,15 +348,18 @@ class VertexAI extends BaseLLM {
|
|||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
const endpoint = new URL("publishers/google/models/code-gecko:predict", this.apiBase);
|
||||
const endpoint = new URL(
|
||||
"publishers/google/models/code-gecko:predict",
|
||||
this.apiBase,
|
||||
);
|
||||
const resp = await this.fetch(endpoint, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
instances: [
|
||||
{
|
||||
prefix: prefix,
|
||||
suffix: suffix
|
||||
}
|
||||
suffix: suffix,
|
||||
},
|
||||
],
|
||||
parameters: {
|
||||
temperature: options.temperature,
|
||||
|
|
@ -363,10 +367,9 @@ class VertexAI extends BaseLLM {
|
|||
stopSequences: options.stop?.splice(0, 5),
|
||||
frequencyPenalty: options.frequencyPenalty,
|
||||
presencePenalty: options.frequencyPenalty,
|
||||
}
|
||||
|
||||
},
|
||||
}),
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
// Streaming is not supported by code-gecko
|
||||
// TODO: convert to non-streaming fim method when one exist in continue.
|
||||
|
|
@ -409,7 +412,7 @@ class VertexAI extends BaseLLM {
|
|||
signal,
|
||||
options,
|
||||
)) {
|
||||
yield stripImages(message.content);
|
||||
yield renderChatMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -419,9 +422,6 @@ class VertexAI extends BaseLLM {
|
|||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
|
||||
|
||||
|
||||
if (this.model === "code-gecko") {
|
||||
yield* this.streamFimGecko(prefix, suffix, signal, options);
|
||||
} else if (this.model.includes("codestral")) {
|
||||
|
|
@ -429,21 +429,15 @@ class VertexAI extends BaseLLM {
|
|||
} else {
|
||||
throw new Error(`Unsupported model: ${this.model}`);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
supportsFim(): boolean {
|
||||
return ["code-gecko", "codestral-latest"].includes(this.model);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
async function delay(seconds: number) {
|
||||
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
||||
}
|
||||
|
||||
|
||||
|
||||
export default VertexAI;
|
||||
|
|
|
|||
|
|
@ -4,25 +4,22 @@ import {
|
|||
LLMOptions,
|
||||
ModelProvider,
|
||||
} from "../../index.js";
|
||||
import { stripImages } from "../images.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamResponse } from "../stream.js";
|
||||
|
||||
let watsonxToken = {
|
||||
expiration: 0,
|
||||
token: ""
|
||||
expiration: 0,
|
||||
token: "",
|
||||
};
|
||||
|
||||
class WatsonX extends BaseLLM {
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
}
|
||||
|
||||
async getBearerToken(): Promise<{ token: string; expiration: number }> {
|
||||
if (
|
||||
this.apiBase?.includes("cloud.ibm.com")
|
||||
) {
|
||||
if (this.apiBase?.includes("cloud.ibm.com")) {
|
||||
// watsonx SaaS
|
||||
const wxToken = await (
|
||||
await fetch(
|
||||
|
|
@ -82,11 +79,9 @@ class WatsonX extends BaseLLM {
|
|||
}
|
||||
|
||||
getWatsonxEndpoint(): string {
|
||||
return (
|
||||
this.deploymentId ?
|
||||
`${this.apiBase}/ml/v1/deployments/${this.deploymentId}/text/generation_stream?version=${this.apiVersion}`:
|
||||
`${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}`
|
||||
);
|
||||
return this.deploymentId
|
||||
? `${this.apiBase}/ml/v1/deployments/${this.deploymentId}/text/generation_stream?version=${this.apiVersion}`
|
||||
: `${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}`;
|
||||
}
|
||||
|
||||
static providerName: ModelProvider = "watsonx";
|
||||
|
|
@ -96,6 +91,10 @@ class WatsonX extends BaseLLM {
|
|||
return message;
|
||||
}
|
||||
|
||||
if (message.role === "tool") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parts = message.content.map((part) => {
|
||||
const msg: any = {
|
||||
type: part.type,
|
||||
|
|
@ -119,7 +118,7 @@ class WatsonX extends BaseLLM {
|
|||
|
||||
protected _convertArgs(options: any, messages: ChatMessage[]) {
|
||||
const finalOptions = {
|
||||
messages: messages.map(this._convertMessage),
|
||||
messages: messages.map(this._convertMessage).filter(Boolean),
|
||||
model: this._convertModelName(options.model),
|
||||
max_tokens: options.maxTokens,
|
||||
temperature: options.temperature,
|
||||
|
|
@ -133,8 +132,9 @@ class WatsonX extends BaseLLM {
|
|||
protected _getHeaders() {
|
||||
return {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `${watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer"
|
||||
} ${watsonxToken.token}`,
|
||||
Authorization: `${
|
||||
watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer"
|
||||
} ${watsonxToken.token}`,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -165,7 +165,7 @@ class WatsonX extends BaseLLM {
|
|||
signal,
|
||||
options,
|
||||
)) {
|
||||
yield stripImages(chunk.content);
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -183,7 +183,8 @@ class WatsonX extends BaseLLM {
|
|||
watsonxToken = await this.getBearerToken();
|
||||
} else {
|
||||
console.log(
|
||||
`Reusing token (expires in ${(watsonxToken.expiration - now) / 60
|
||||
`Reusing token (expires in ${
|
||||
(watsonxToken.expiration - now) / 60
|
||||
} mins)`,
|
||||
);
|
||||
}
|
||||
|
|
@ -191,7 +192,8 @@ class WatsonX extends BaseLLM {
|
|||
throw new Error("Something went wrong. Check your credentials, please.");
|
||||
}
|
||||
const stopSequences =
|
||||
options.stop?.slice(0,6) ?? (options.model?.includes("granite") ? ["Question:"] : []);
|
||||
options.stop?.slice(0, 6) ??
|
||||
(options.model?.includes("granite") ? ["Question:"] : []);
|
||||
const url = this.getWatsonxEndpoint();
|
||||
const headers = this._getHeaders();
|
||||
|
||||
|
|
@ -224,7 +226,7 @@ class WatsonX extends BaseLLM {
|
|||
method: "POST",
|
||||
headers: headers,
|
||||
body: JSON.stringify(payload),
|
||||
signal
|
||||
signal,
|
||||
});
|
||||
|
||||
if (!response.ok || response.body === null) {
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ import Deepseek from "./Deepseek";
|
|||
import Fireworks from "./Fireworks";
|
||||
import Flowise from "./Flowise";
|
||||
import FreeTrial from "./FreeTrial";
|
||||
import FunctionNetwork from "./FunctionNetwork";
|
||||
import Gemini from "./Gemini";
|
||||
import Groq from "./Groq";
|
||||
import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI";
|
||||
|
|
@ -54,6 +55,7 @@ const LLMs = [
|
|||
Anthropic,
|
||||
Cohere,
|
||||
FreeTrial,
|
||||
FunctionNetwork,
|
||||
Gemini,
|
||||
Llamafile,
|
||||
Moonshot,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ChatMessage } from "../../index.js";
|
||||
import { stripImages } from "../images.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
|
||||
function templateFactory(
|
||||
systemMessage: (msg: ChatMessage) => string,
|
||||
|
|
@ -64,7 +64,7 @@ function llama2TemplateMessages(msgs: ChatMessage[]): string {
|
|||
let prompt = "";
|
||||
let hasSystem = msgs[0].role === "system";
|
||||
|
||||
if (hasSystem && stripImages(msgs[0].content).trim() === "") {
|
||||
if (hasSystem && renderChatMessage(msgs[0]).trim() === "") {
|
||||
hasSystem = false;
|
||||
msgs = msgs.slice(1);
|
||||
}
|
||||
|
|
@ -158,7 +158,7 @@ function deepseekTemplateMessages(msgs: ChatMessage[]): string {
|
|||
prompt +=
|
||||
"You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n";
|
||||
if (msgs[0].role === "system") {
|
||||
system = stripImages(msgs.shift()!.content);
|
||||
system = renderChatMessage(msgs.shift()!);
|
||||
}
|
||||
|
||||
for (let i = 0; i < msgs.length; i++) {
|
||||
|
|
@ -245,7 +245,7 @@ function codeLlama70bTemplateMessages(msgs: ChatMessage[]): string {
|
|||
let prompt = "<s>";
|
||||
|
||||
for (const msg of msgs) {
|
||||
prompt += `Source: ${msg.role}\n\n ${stripImages(msg.content).trim()}`;
|
||||
prompt += `Source: ${msg.role}\n\n ${renderChatMessage(msg).trim()}`;
|
||||
prompt += " <step> ";
|
||||
}
|
||||
|
||||
|
|
|
|||
435
core/package-lock.json
generated
435
core/package-lock.json
generated
|
|
@ -14,6 +14,7 @@
|
|||
"@aws-sdk/credential-providers": "^3.620.1",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/llm-info": "^1.0.2",
|
||||
"@modelcontextprotocol/sdk": "^1.0.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.0.2",
|
||||
"@typescript-eslint/eslint-plugin": "^7.8.0",
|
||||
|
|
@ -47,6 +48,7 @@
|
|||
"onnxruntime-node": "1.14.0",
|
||||
"openai": "^4.20.1",
|
||||
"p-limit": "^6.1.0",
|
||||
"partial-json": "^0.1.7",
|
||||
"pg": "^8.11.3",
|
||||
"posthog-node": "^3.6.3",
|
||||
"puppeteer": "^22.4.0",
|
||||
|
|
@ -3381,6 +3383,70 @@
|
|||
"resolved": "https://registry.npmjs.org/@continuedev/llm-info/-/llm-info-1.0.2.tgz",
|
||||
"integrity": "sha512-B5VFcZlwlwQg6htbIjCjj3z/pj3I929BzgWowiLzxYC40ag+v3e/hM9EDGWCEdNIT+PDMchAwS67iNB+WhE7qg=="
|
||||
},
|
||||
"node_modules/@esbuild/android-arm": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz",
|
||||
"integrity": "sha512-rIKddzqhmav7MSmoFCmDIb6e2W57geRsM94gV2l38fzhXMwq7hZoClug9USI2pFRGL06f4IOPHHpFNOkWieR8A==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.17.19.tgz",
|
||||
"integrity": "sha512-KBMWvEZooR7+kzY0BtbTQn0OAYY7CsiydT63pVEaPtVYF0hXbUaOyZog37DKxK7NF3XacBJOpYT4adIJh+avxA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.17.19.tgz",
|
||||
"integrity": "sha512-uUTTc4xGNDT7YSArp/zbtmbhO0uEEK9/ETW29Wk1thYUJBz3IVnvgEiEwEa9IeLyvnpKrWK64Utw2bgUmDveww==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-arm64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.17.19.tgz",
|
||||
"integrity": "sha512-80wEoCfF/hFKM6WE1FyBHc9SfUblloAWx6FJkFWTWiCoht9Mc0ARGEM47e67W9rI09YoUxJL68WHfDRYEAvOhg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.19.tgz",
|
||||
|
|
@ -3397,6 +3463,278 @@
|
|||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-arm64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.17.19.tgz",
|
||||
"integrity": "sha512-pBwbc7DufluUeGdjSU5Si+P3SoMF5DQ/F/UmTSb8HXO80ZEAJmrykPyzo1IfNbAoaqw48YRpv8shwd1NoI0jcQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.17.19.tgz",
|
||||
"integrity": "sha512-4lu+n8Wk0XlajEhbEffdy2xy53dpR06SlzvhGByyg36qJw6Kpfk7cp45DR/62aPH9mtJRmIyrXAS5UWBrJT6TQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.17.19.tgz",
|
||||
"integrity": "sha512-cdmT3KxjlOQ/gZ2cjfrQOtmhG4HJs6hhvm3mWSRDPtZ/lP5oe8FWceS10JaSJC13GBd4eH/haHnqf7hhGNLerA==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.19.tgz",
|
||||
"integrity": "sha512-ct1Tg3WGwd3P+oZYqic+YZF4snNl2bsnMKRkb3ozHmnM0dGWuxcPTTntAF6bOP0Sp4x0PjSF+4uHQ1xvxfRKqg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ia32": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.17.19.tgz",
|
||||
"integrity": "sha512-w4IRhSy1VbsNxHRQpeGCHEmibqdTUx61Vc38APcsRbuVgK0OPEnQ0YD39Brymn96mOx48Y2laBQGqgZ0j9w6SQ==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-loong64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.17.19.tgz",
|
||||
"integrity": "sha512-2iAngUbBPMq439a+z//gE+9WBldoMp1s5GWsUSgqHLzLJ9WoZLZhpwWuym0u0u/4XmZ3gpHmzV84PonE+9IIdQ==",
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-mips64el": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.17.19.tgz",
|
||||
"integrity": "sha512-LKJltc4LVdMKHsrFe4MGNPp0hqDFA1Wpt3jE1gEyM3nKUvOiO//9PheZZHfYRfYl6AwdTH4aTcXSqBerX0ml4A==",
|
||||
"cpu": [
|
||||
"mips64el"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ppc64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.17.19.tgz",
|
||||
"integrity": "sha512-/c/DGybs95WXNS8y3Ti/ytqETiW7EU44MEKuCAcpPto3YjQbyK3IQVKfF6nbghD7EcLUGl0NbiL5Rt5DMhn5tg==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-riscv64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.17.19.tgz",
|
||||
"integrity": "sha512-FC3nUAWhvFoutlhAkgHf8f5HwFWUL6bYdvLc/TTuxKlvLi3+pPzdZiFKSWz/PF30TB1K19SuCxDTI5KcqASJqA==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-s390x": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.17.19.tgz",
|
||||
"integrity": "sha512-IbFsFbxMWLuKEbH+7sTkKzL6NJmG2vRyy6K7JJo55w+8xDk7RElYn6xvXtDW8HCfoKBFK69f3pgBJSUSQPr+4Q==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.19.tgz",
|
||||
"integrity": "sha512-68ngA9lg2H6zkZcyp22tsVt38mlhWde8l3eJLWkyLrp4HwMUr3c1s/M2t7+kHIhvMjglIBrFpncX1SzMckomGw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.19.tgz",
|
||||
"integrity": "sha512-CwFq42rXCR8TYIjIfpXCbRX0rp1jo6cPIUPSaWwzbVI4aOfX96OXY8M6KNmtPcg7QjYeDmN+DD0Wp3LaBOLf4Q==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.19.tgz",
|
||||
"integrity": "sha512-cnq5brJYrSZ2CF6c35eCmviIN3k3RczmHz8eYaVlNasVqsNY+JKohZU5MKmaOI+KkllCdzOKKdPs762VCPC20g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/sunos-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.19.tgz",
|
||||
"integrity": "sha512-vCRT7yP3zX+bKWFeP/zdS6SqdWB8OIpaRq/mbXQxTGHnIxspRtigpkUcDMlSCOejlHowLqII7K2JKevwyRP2rg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"sunos"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-arm64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.19.tgz",
|
||||
"integrity": "sha512-yYx+8jwowUstVdorcMdNlzklLYhPxjniHWFKgRqH7IFlUEa0Umu3KuYplf1HUZZ422e3NU9F4LGb+4O0Kdcaag==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-ia32": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.17.19.tgz",
|
||||
"integrity": "sha512-eggDKanJszUtCdlVs0RB+h35wNlb5v4TWEkq4vZcmVt5u/HiDZrTXe2bWFQUez3RgNHwx/x4sk5++4NSSicKkw==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-x64": {
|
||||
"version": "0.17.19",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz",
|
||||
"integrity": "sha512-lAhycmKnVOuRYNtRtatQR1LPQf2oYCkRGkSFnseDAKPl8lu5SOsK/e1sXe5a0Pc5kHIHe6P2I/ilntNv2xf3cA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@eslint-community/eslint-utils": {
|
||||
"version": "4.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz",
|
||||
|
|
@ -4155,6 +4493,16 @@
|
|||
"win32"
|
||||
]
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/sdk": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.0.0.tgz",
|
||||
"integrity": "sha512-mbe0otw8vTtZoL5pVucXAmx6oEC7YjdXBgVeFkJXASu4OAnLkrIeNw9zwzU5CwEp19M54bjOUGcna90Dl/H5Bw==",
|
||||
"dependencies": {
|
||||
"content-type": "^1.0.5",
|
||||
"raw-body": "^3.0.0",
|
||||
"zod": "^3.23.8"
|
||||
}
|
||||
},
|
||||
"node_modules/@mozilla/readability": {
|
||||
"version": "0.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@mozilla/readability/-/readability-0.5.0.tgz",
|
||||
|
|
@ -6557,6 +6905,14 @@
|
|||
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/bytes": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/cacache": {
|
||||
"version": "15.3.0",
|
||||
"resolved": "https://registry.npmjs.org/cacache/-/cacache-15.3.0.tgz",
|
||||
|
|
@ -6996,6 +7352,14 @@
|
|||
"resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",
|
||||
"integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ=="
|
||||
},
|
||||
"node_modules/content-type": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
|
||||
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/convert-source-map": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
|
||||
|
|
@ -7379,6 +7743,14 @@
|
|||
"node": ">=0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/depd": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
|
||||
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/deprecation": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz",
|
||||
|
|
@ -9343,6 +9715,21 @@
|
|||
"integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/http-errors": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
|
||||
"integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==",
|
||||
"dependencies": {
|
||||
"depd": "2.0.0",
|
||||
"inherits": "2.0.4",
|
||||
"setprototypeof": "1.2.0",
|
||||
"statuses": "2.0.1",
|
||||
"toidentifier": "1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/http-proxy-agent": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
|
||||
|
|
@ -12497,6 +12884,11 @@
|
|||
"url": "https://github.com/inikulin/parse5?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/partial-json": {
|
||||
"version": "0.1.7",
|
||||
"resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz",
|
||||
"integrity": "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA=="
|
||||
},
|
||||
"node_modules/path-exists": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
|
||||
|
|
@ -13262,6 +13654,20 @@
|
|||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/raw-body": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.0.tgz",
|
||||
"integrity": "sha512-RmkhL8CAyCRPXCE28MMH0z2PNWQBNk2Q09ZdxM9IOOXwxwZbN+qbWaatPkdkWIKL2ZVDImrN/pK5HTRz2PcS4g==",
|
||||
"dependencies": {
|
||||
"bytes": "3.1.2",
|
||||
"http-errors": "2.0.0",
|
||||
"iconv-lite": "0.6.3",
|
||||
"unpipe": "1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/rc": {
|
||||
"version": "1.2.8",
|
||||
"resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
|
||||
|
|
@ -13740,6 +14146,11 @@
|
|||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/setprototypeof": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
|
||||
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="
|
||||
},
|
||||
"node_modules/sharp": {
|
||||
"version": "0.32.6",
|
||||
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.32.6.tgz",
|
||||
|
|
@ -14134,6 +14545,14 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/statuses": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
|
||||
"integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/stoppable": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/stoppable/-/stoppable-1.1.0.tgz",
|
||||
|
|
@ -14626,6 +15045,14 @@
|
|||
"node": ">=8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/toidentifier": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
|
||||
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/tough-cookie": {
|
||||
"version": "4.1.4",
|
||||
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz",
|
||||
|
|
@ -15042,6 +15469,14 @@
|
|||
"node": ">= 4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/unpipe": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
|
||||
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/update-browserslist-db": {
|
||||
"version": "1.0.16",
|
||||
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.16.tgz",
|
||||
|
|
|
|||
|
|
@ -45,6 +45,7 @@
|
|||
"@aws-sdk/credential-providers": "^3.620.1",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/llm-info": "^1.0.2",
|
||||
"@modelcontextprotocol/sdk": "^1.0.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.0.2",
|
||||
"@typescript-eslint/eslint-plugin": "^7.8.0",
|
||||
|
|
@ -78,6 +79,7 @@
|
|||
"onnxruntime-node": "1.14.0",
|
||||
"openai": "^4.20.1",
|
||||
"p-limit": "^6.1.0",
|
||||
"partial-json": "^0.1.7",
|
||||
"pg": "^8.11.3",
|
||||
"posthog-node": "^3.6.3",
|
||||
"puppeteer": "^22.4.0",
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import * as YAML from "yaml";
|
||||
|
||||
import { ContinueSDK, SlashCommand } from "../..";
|
||||
import { stripImages } from "../../llm/images";
|
||||
import { getBasename } from "../../util/index";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
|
||||
import { getContextProviderHelpers } from "./getContextProviderHelpers";
|
||||
import { renderTemplatedString } from "./renderTemplatedString";
|
||||
|
|
@ -90,8 +90,11 @@ export function slashCommandFromPromptFile(
|
|||
systemMessage,
|
||||
);
|
||||
|
||||
for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) {
|
||||
yield stripImages(chunk.content);
|
||||
for await (const chunk of context.llm.streamChat(
|
||||
messages,
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -4,21 +4,21 @@ import { ProfileDescription } from "../config/ConfigHandler";
|
|||
import type {
|
||||
BrowserSerializedContinueConfig,
|
||||
ChatMessage,
|
||||
ContextItem,
|
||||
ContextItemWithId,
|
||||
ContextSubmenuItem,
|
||||
DiffLine,
|
||||
FileSymbolMap,
|
||||
IdeSettings,
|
||||
IndexingStatus,
|
||||
LLMFullCompletionOptions,
|
||||
MessageContent,
|
||||
ModelDescription,
|
||||
ModelRoles,
|
||||
Session,
|
||||
RangeInFile,
|
||||
SerializedContinueConfig,
|
||||
Session,
|
||||
SessionMetadata,
|
||||
SiteIndexingConfig,
|
||||
ToolCall,
|
||||
} from "../";
|
||||
|
||||
export type ProtocolGeneratorType<T> = AsyncGenerator<{
|
||||
|
|
@ -123,7 +123,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
completionOptions: LLMFullCompletionOptions;
|
||||
title: string;
|
||||
},
|
||||
ProtocolGeneratorType<MessageContent>,
|
||||
ProtocolGeneratorType<ChatMessage>,
|
||||
];
|
||||
streamDiffLines: [
|
||||
{
|
||||
|
|
@ -174,4 +174,5 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
"profiles/switch": [{ id: string }, undefined];
|
||||
|
||||
"auth/getAuthUrl": [undefined, { url: string }];
|
||||
"tools/call": [{ toolCall: ToolCall }, { contextItems: ContextItem[] }];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
|||
{ accept: boolean; onlyFirst: boolean; filepath: string },
|
||||
void,
|
||||
];
|
||||
"edit/escape": [undefined, void];
|
||||
"edit/exit": [{ shouldFocusEditor: boolean }, void];
|
||||
};
|
||||
|
||||
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
||||
|
|
|
|||
|
|
@ -58,6 +58,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"addAutocompleteModel",
|
||||
"profiles/switch",
|
||||
"didChangeSelectedProfile",
|
||||
"tools/call",
|
||||
];
|
||||
|
||||
// Message types to pass through from core to webview
|
||||
|
|
|
|||
11
core/tools/builtIn.ts
Normal file
11
core/tools/builtIn.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
export enum BuiltInToolNames {
|
||||
ReadFile = "read_file",
|
||||
ReadCurrentlyOpenFile = "read_currently_open_file",
|
||||
CreateNewFile = "create_new_file",
|
||||
RunTerminalCommand = "run_terminal_command",
|
||||
ViewSubdirectory = "view_subdirectory",
|
||||
ViewRepoMap = "view_repo_map",
|
||||
ExactSearch = "exact_search",
|
||||
SearchWeb = "search_web",
|
||||
ViewDiff = "view_diff",
|
||||
}
|
||||
109
core/tools/callTool.ts
Normal file
109
core/tools/callTool.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
import { ContextItem, ToolExtras } from "..";
|
||||
import MCPConnectionSingleton from "../context/mcp";
|
||||
import { BuiltInToolNames } from "./builtIn";
|
||||
|
||||
import { createNewFileImpl } from "./implementations/createNewFile";
|
||||
import { exactSearchImpl } from "./implementations/exactSearch";
|
||||
import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile";
|
||||
import { readFileImpl } from "./implementations/readFile";
|
||||
import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
|
||||
import { searchWebImpl } from "./implementations/searchWeb";
|
||||
import { viewDiffImpl } from "./implementations/viewDiff";
|
||||
import { viewRepoMapImpl } from "./implementations/viewRepoMap";
|
||||
import { viewSubdirectoryImpl } from "./implementations/viewSubdirectory";
|
||||
|
||||
async function callHttpTool(
|
||||
url: string,
|
||||
args: any,
|
||||
extras: ToolExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const response = await extras.fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
arguments: args,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to call tool: ${url}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.output;
|
||||
}
|
||||
|
||||
async function callToolFromUri(
|
||||
uri: string,
|
||||
args: any,
|
||||
extras: ToolExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const canParse = URL.canParse(uri);
|
||||
if (!canParse) {
|
||||
throw new Error(`Invalid URI: ${uri}`);
|
||||
}
|
||||
const parsedUri = new URL(uri);
|
||||
|
||||
switch (parsedUri?.protocol) {
|
||||
case "http:":
|
||||
case "https:":
|
||||
return callHttpTool(uri, args, extras);
|
||||
case "mcp:":
|
||||
const client = await MCPConnectionSingleton.getExistingInstance();
|
||||
if (!client) {
|
||||
throw new Error("MCP connection not found");
|
||||
}
|
||||
const toolName = parsedUri!.hostname;
|
||||
const response = await client.client.callTool({
|
||||
name: toolName,
|
||||
arguments: args,
|
||||
});
|
||||
|
||||
if (response.isError === true) {
|
||||
throw new Error(`Failed to call tool: ${toolName}`);
|
||||
}
|
||||
|
||||
return (response.content as any).map((item: any) => {
|
||||
if (item.type !== "text") {
|
||||
throw new Error(
|
||||
`Continue received item of type "${item.type}" from MCP tool, but currently only supports "text".`,
|
||||
);
|
||||
}
|
||||
return { name: toolName, description: toolName, content: item.text };
|
||||
});
|
||||
|
||||
default:
|
||||
throw new Error(`Unsupported protocol: ${parsedUri?.protocol}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function callTool(
|
||||
uri: string,
|
||||
args: any,
|
||||
extras: ToolExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
switch (uri) {
|
||||
case BuiltInToolNames.ReadFile:
|
||||
return await readFileImpl(args, extras);
|
||||
case BuiltInToolNames.CreateNewFile:
|
||||
return await createNewFileImpl(args, extras);
|
||||
case BuiltInToolNames.ExactSearch:
|
||||
return await exactSearchImpl(args, extras);
|
||||
case BuiltInToolNames.RunTerminalCommand:
|
||||
return await runTerminalCommandImpl(args, extras);
|
||||
case BuiltInToolNames.SearchWeb:
|
||||
return await searchWebImpl(args, extras);
|
||||
case BuiltInToolNames.ViewDiff:
|
||||
return await viewDiffImpl(args, extras);
|
||||
case BuiltInToolNames.ViewRepoMap:
|
||||
return await viewRepoMapImpl(args, extras);
|
||||
case BuiltInToolNames.ViewSubdirectory:
|
||||
return await viewSubdirectoryImpl(args, extras);
|
||||
case BuiltInToolNames.ReadCurrentlyOpenFile:
|
||||
return await readCurrentlyOpenFileImpl(args, extras);
|
||||
default:
|
||||
return await callToolFromUri(uri, args, extras);
|
||||
}
|
||||
}
|
||||
27
core/tools/definitions/createNewFile.ts
Normal file
27
core/tools/definitions/createNewFile.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { Tool } from "../..";
|
||||
import { BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const createNewFileTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Create New File",
|
||||
wouldLikeTo: "create a new file",
|
||||
readonly: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.CreateNewFile,
|
||||
description: "Create a new file",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "contents"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description: "The path where the new file should be created",
|
||||
},
|
||||
contents: {
|
||||
type: "string",
|
||||
description: "The contents to write to the new file",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
24
core/tools/definitions/exactSearch.ts
Normal file
24
core/tools/definitions/exactSearch.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { Tool } from "../..";
|
||||
import { BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const exactSearchTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Exact Search",
|
||||
wouldLikeTo: 'search for "{{{ query }}}" in the repository',
|
||||
readonly: true,
|
||||
function: {
|
||||
name: BuiltInToolNames.ExactSearch,
|
||||
description: "Perform an exact search over the repository using ripgrep.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["query"],
|
||||
properties: {
|
||||
query: {
|
||||
type: "string",
|
||||
description:
|
||||
"The search query to use. Must be a valid ripgrep regex expression, escaped where needed",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
18
core/tools/definitions/readCurrentlyOpenFile.ts
Normal file
18
core/tools/definitions/readCurrentlyOpenFile.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { Tool } from "../..";
|
||||
import { BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const readCurrentlyOpenFileTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Read Currently Open File",
|
||||
wouldLikeTo: "read the current file",
|
||||
readonly: true,
|
||||
function: {
|
||||
name: BuiltInToolNames.ReadCurrentlyOpenFile,
|
||||
description:
|
||||
"Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, this is probably it.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {},
|
||||
},
|
||||
},
|
||||
};
|
||||
25
core/tools/definitions/readFile.ts
Normal file
25
core/tools/definitions/readFile.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { Tool } from "../..";
|
||||
import { BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const readFileTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Read File",
|
||||
wouldLikeTo: "read {{{ filepath }}}",
|
||||
readonly: true,
|
||||
function: {
|
||||
name: BuiltInToolNames.ReadFile,
|
||||
description:
|
||||
"Use this tool whenever you need to view the contents of a file.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path of the file to read, relative to the root of the workspace.",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
25
core/tools/definitions/runTerminalCommand.ts
Normal file
25
core/tools/definitions/runTerminalCommand.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { Tool } from "../..";
|
||||
import { BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const runTerminalCommandTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Run Terminal Command",
|
||||
wouldLikeTo: "run a terminal command",
|
||||
readonly: false,
|
||||
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.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["command"],
|
||||
properties: {
|
||||
command: {
|
||||
type: "string",
|
||||
description:
|
||||
"The command to run. This will be passed directly into the shell.",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
25
core/tools/definitions/searchWeb.ts
Normal file
25
core/tools/definitions/searchWeb.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { Tool } from "../..";
|
||||
|
||||
import { BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const searchWebTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Search Web",
|
||||
wouldLikeTo: 'search the web for "{{{ query }}}"',
|
||||
readonly: true,
|
||||
function: {
|
||||
name: BuiltInToolNames.SearchWeb,
|
||||
description:
|
||||
"Performs a web search, returning top results. This tool should only be called for questions that require external knowledge. Common programming questions do not require web search.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["query"],
|
||||
properties: {
|
||||
repo_url: {
|
||||
type: "string",
|
||||
description: "The natural language search query",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
18
core/tools/definitions/viewDiff.ts
Normal file
18
core/tools/definitions/viewDiff.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { Tool } from "../..";
|
||||
|
||||
import { BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const viewDiffTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "View Diff",
|
||||
wouldLikeTo: "view a diff",
|
||||
readonly: true,
|
||||
function: {
|
||||
name: BuiltInToolNames.ViewDiff,
|
||||
description: "View the current diff of working changes",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {},
|
||||
},
|
||||
},
|
||||
};
|
||||
18
core/tools/definitions/viewRepoMap.ts
Normal file
18
core/tools/definitions/viewRepoMap.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { Tool } from "../..";
|
||||
|
||||
import { BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const viewRepoMapTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "View Repo Map",
|
||||
wouldLikeTo: "view the repository map",
|
||||
readonly: true,
|
||||
function: {
|
||||
name: BuiltInToolNames.ViewRepoMap,
|
||||
description: "View the repository map",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {},
|
||||
},
|
||||
},
|
||||
};
|
||||
24
core/tools/definitions/viewSubdirectory.ts
Normal file
24
core/tools/definitions/viewSubdirectory.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { Tool } from "../..";
|
||||
import { BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const viewSubdirectoryTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "View Subdirectory",
|
||||
wouldLikeTo: 'view the contents of "{{{ directory_path }}}"',
|
||||
readonly: true,
|
||||
function: {
|
||||
name: BuiltInToolNames.ViewSubdirectory,
|
||||
description: "View the contents of a subdirectory",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["directory_path"],
|
||||
properties: {
|
||||
directory_path: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path of the subdirectory to view, relative to the root of the workspace",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
17
core/tools/implementations/createNewFile.ts
Normal file
17
core/tools/implementations/createNewFile.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { getPathModuleForIde } from "../../util/pathModule";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
|
||||
export const createNewFileImpl: ToolImpl = async (args, extras) => {
|
||||
const pathSep = await extras.ide.pathSep();
|
||||
let filepath = args.filepath;
|
||||
if (!args.filepath.startsWith(pathSep)) {
|
||||
const pathModule = await getPathModuleForIde(extras.ide);
|
||||
const workspaceDirs = await extras.ide.getWorkspaceDirs();
|
||||
const cwd = workspaceDirs[0];
|
||||
filepath = pathModule.join(cwd, filepath);
|
||||
}
|
||||
await extras.ide.writeFile(filepath, args.contents);
|
||||
await extras.ide.openFile(filepath);
|
||||
return [];
|
||||
};
|
||||
12
core/tools/implementations/exactSearch.ts
Normal file
12
core/tools/implementations/exactSearch.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { ToolImpl } from ".";
|
||||
|
||||
export const exactSearchImpl: ToolImpl = async (args, extras) => {
|
||||
const content = await extras.ide.getSearchResults(args.query);
|
||||
return [
|
||||
{
|
||||
name: "Search results",
|
||||
description: "Results from exact search",
|
||||
content,
|
||||
},
|
||||
];
|
||||
};
|
||||
6
core/tools/implementations/index.ts
Normal file
6
core/tools/implementations/index.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
import { ContextItem, ToolExtras } from "../..";
|
||||
|
||||
export type ToolImpl = (
|
||||
parameters: any,
|
||||
extras: ToolExtras,
|
||||
) => Promise<ContextItem[]>;
|
||||
20
core/tools/implementations/readCurrentlyOpenFile.ts
Normal file
20
core/tools/implementations/readCurrentlyOpenFile.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { getBasename } from "../../util";
|
||||
|
||||
export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => {
|
||||
const result = await extras.ide.getCurrentFile();
|
||||
|
||||
if (!result) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const basename = getBasename(result.path);
|
||||
|
||||
return [
|
||||
{
|
||||
name: "Current file",
|
||||
description: basename,
|
||||
content: `\`\`\`${basename}\n${result.contents}\n\`\`\``,
|
||||
},
|
||||
];
|
||||
};
|
||||
14
core/tools/implementations/readFile.ts
Normal file
14
core/tools/implementations/readFile.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { getBasename } from "../../util";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
|
||||
export const readFileImpl: ToolImpl = async (args, extras) => {
|
||||
const content = await extras.ide.readFile(args.filepath);
|
||||
return [
|
||||
{
|
||||
name: getBasename(args.filepath),
|
||||
description: args.filepath,
|
||||
content,
|
||||
},
|
||||
];
|
||||
};
|
||||
40
core/tools/implementations/runTerminalCommand.ts
Normal file
40
core/tools/implementations/runTerminalCommand.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import { ToolImpl } from ".";
|
||||
const util = require("node:util");
|
||||
const asyncExec = util.promisify(require("node:child_process").exec);
|
||||
|
||||
export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
||||
const ideInfo = await extras.ide.getIdeInfo();
|
||||
|
||||
if (ideInfo.remoteName === "local" || ideInfo.remoteName === "") {
|
||||
try {
|
||||
const output = await asyncExec(args.command, {
|
||||
cwd: (await extras.ide.getWorkspaceDirs())[0],
|
||||
});
|
||||
return [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: output.stdout ?? "",
|
||||
},
|
||||
];
|
||||
} catch (error: any) {
|
||||
return [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: error.stderr ?? error.toString(),
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
await extras.ide.runCommand(args.command);
|
||||
return [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content:
|
||||
"[Terminal output not available. This is only available in local development environments and not in SSH environments for example.]",
|
||||
},
|
||||
];
|
||||
};
|
||||
8
core/tools/implementations/searchWeb.ts
Normal file
8
core/tools/implementations/searchWeb.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import { fetchSearchResults } from "../../context/providers/WebContextProvider";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
|
||||
export const searchWebImpl: ToolImpl = async (args, extras) => {
|
||||
const webResults = await fetchSearchResults(args.query, 5, extras.fetch);
|
||||
return webResults;
|
||||
};
|
||||
12
core/tools/implementations/viewDiff.ts
Normal file
12
core/tools/implementations/viewDiff.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { ToolImpl } from ".";
|
||||
|
||||
export const viewDiffImpl: ToolImpl = async (args, extras) => {
|
||||
const diff = await extras.ide.getDiff(true);
|
||||
return [
|
||||
{
|
||||
name: "Diff",
|
||||
description: "The current git diff",
|
||||
content: diff.join("\n"),
|
||||
},
|
||||
];
|
||||
};
|
||||
14
core/tools/implementations/viewRepoMap.ts
Normal file
14
core/tools/implementations/viewRepoMap.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import generateRepoMap from "../../util/generateRepoMap";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
|
||||
export const viewRepoMapImpl: ToolImpl = async (args, extras) => {
|
||||
const repoMap = await generateRepoMap(extras.llm, extras.ide, {});
|
||||
return [
|
||||
{
|
||||
name: "Repo map",
|
||||
description: "Overview of the repository structure",
|
||||
content: repoMap,
|
||||
},
|
||||
];
|
||||
};
|
||||
27
core/tools/implementations/viewSubdirectory.ts
Normal file
27
core/tools/implementations/viewSubdirectory.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import generateRepoMap from "../../util/generateRepoMap";
|
||||
import { resolveRelativePathInWorkspace } from "../../util/ideUtils";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
|
||||
export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => {
|
||||
const { directory_path } = args;
|
||||
const absolutePath = await resolveRelativePathInWorkspace(
|
||||
directory_path,
|
||||
extras.ide,
|
||||
);
|
||||
|
||||
if (!absolutePath) {
|
||||
throw new Error(`Directory path "${directory_path}" does not exist.`);
|
||||
}
|
||||
|
||||
const repoMap = await generateRepoMap(extras.llm, extras.ide, {
|
||||
dirs: [absolutePath],
|
||||
});
|
||||
return [
|
||||
{
|
||||
name: "Repo map",
|
||||
description: `Map of ${directory_path}`,
|
||||
content: repoMap,
|
||||
},
|
||||
];
|
||||
};
|
||||
21
core/tools/index.ts
Normal file
21
core/tools/index.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import { createNewFileTool } from "./definitions/createNewFile";
|
||||
import { exactSearchTool } from "./definitions/exactSearch";
|
||||
import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile";
|
||||
import { readFileTool } from "./definitions/readFile";
|
||||
import { runTerminalCommandTool } from "./definitions/runTerminalCommand";
|
||||
import { searchWebTool } from "./definitions/searchWeb";
|
||||
import { viewDiffTool } from "./definitions/viewDiff";
|
||||
import { viewRepoMapTool } from "./definitions/viewRepoMap";
|
||||
import { viewSubdirectoryTool } from "./definitions/viewSubdirectory";
|
||||
|
||||
export const allTools = [
|
||||
readFileTool,
|
||||
createNewFileTool,
|
||||
runTerminalCommandTool,
|
||||
viewSubdirectoryTool,
|
||||
viewRepoMapTool,
|
||||
exactSearchTool,
|
||||
searchWebTool,
|
||||
viewDiffTool,
|
||||
readCurrentlyOpenFileTool,
|
||||
];
|
||||
|
|
@ -1,5 +1,4 @@
|
|||
import { ILLM, LLMFullCompletionOptions } from "..";
|
||||
import { stripImages } from "../llm/images";
|
||||
|
||||
import { removeQuotesAndEscapes } from ".";
|
||||
|
||||
|
|
@ -35,7 +34,6 @@ export class ChatDescriber {
|
|||
}
|
||||
|
||||
// Clean up and distill the message we want to send to the LLM
|
||||
message = stripImages(message);
|
||||
message = removeCodeBlocksAndTrim(message);
|
||||
|
||||
if (!message) {
|
||||
|
|
|
|||
|
|
@ -96,7 +96,6 @@ class HistoryManager {
|
|||
title: session.title,
|
||||
workspaceDirectory: session.workspaceDirectory,
|
||||
history: session.history,
|
||||
checkpoints: session.checkpoints,
|
||||
};
|
||||
fs.writeFileSync(
|
||||
getSessionFilePath(session.sessionId),
|
||||
|
|
|
|||
13
core/util/incrementalParseJson.ts
Normal file
13
core/util/incrementalParseJson.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { parse } from "partial-json";
|
||||
|
||||
export function incrementalParseJson(raw: string): [boolean, any] {
|
||||
try {
|
||||
return [true, JSON.parse(raw)];
|
||||
} catch (e) {
|
||||
try {
|
||||
return [false, parse(raw)];
|
||||
} catch (e2) {
|
||||
return [false, {}];
|
||||
}
|
||||
}
|
||||
}
|
||||
45
core/util/messageContent.ts
Normal file
45
core/util/messageContent.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import {
|
||||
ChatMessage,
|
||||
ContextItem,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
} from "../index.js";
|
||||
|
||||
export function stripImages(messageContent: MessageContent): string {
|
||||
if (typeof messageContent === "string") {
|
||||
return messageContent;
|
||||
}
|
||||
|
||||
return messageContent
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => part.text)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
export function renderChatMessage(message: ChatMessage): string {
|
||||
switch (message.role) {
|
||||
case "user":
|
||||
case "assistant":
|
||||
case "system":
|
||||
return stripImages(message.content);
|
||||
case "tool":
|
||||
return message.content;
|
||||
}
|
||||
}
|
||||
|
||||
export function renderContextItems(contextItems: ContextItem[]): string {
|
||||
return contextItems.map((item) => item.content).join("\n\n");
|
||||
}
|
||||
|
||||
export function normalizeToMessageParts(message: ChatMessage): MessagePart[] {
|
||||
switch (message.role) {
|
||||
case "user":
|
||||
case "assistant":
|
||||
case "system":
|
||||
return Array.isArray(message.content)
|
||||
? message.content
|
||||
: [{ type: "text", text: message.content }];
|
||||
case "tool":
|
||||
return [{ type: "text", text: message.content }];
|
||||
}
|
||||
}
|
||||
|
|
@ -4,11 +4,13 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
|
|||
disable: false,
|
||||
useFileSuffix: true,
|
||||
maxPromptTokens: 1024,
|
||||
prefixPercentage: 0.85,
|
||||
maxSuffixPercentage: 0.25,
|
||||
prefixPercentage: 0.3,
|
||||
maxSuffixPercentage: 0.2,
|
||||
debounceDelay: 350,
|
||||
multilineCompletions: "auto",
|
||||
// @deprecated TO BE REMOVED
|
||||
slidingWindowPrefixPercentage: 0.75,
|
||||
// @deprecated TO BE REMOVED
|
||||
slidingWindowSize: 500,
|
||||
useCache: true,
|
||||
onlyMyCode: true,
|
||||
|
|
|
|||
|
|
@ -2,10 +2,28 @@ import os from "node:os";
|
|||
|
||||
import { TeamAnalytics } from "../control-plane/TeamAnalytics.js";
|
||||
import { IdeInfo } from "../index.js";
|
||||
import type { PostHog as PostHogType } from "posthog-node";
|
||||
|
||||
export enum PosthogFeatureFlag {
|
||||
AutocompleteTemperature = "autocomplete-temperature",
|
||||
}
|
||||
|
||||
export const EXPERIMENTS: {
|
||||
[key in PosthogFeatureFlag]: {
|
||||
[key: string]: { value: number };
|
||||
};
|
||||
} = {
|
||||
[PosthogFeatureFlag.AutocompleteTemperature]: {
|
||||
control: { value: 0.01 },
|
||||
"0_33": { value: 0.33 },
|
||||
"0_66": { value: 0.66 },
|
||||
"0_99": { value: 0.99 },
|
||||
},
|
||||
};
|
||||
|
||||
export class Telemetry {
|
||||
// Set to undefined whenever telemetry is disabled
|
||||
static client: any = undefined;
|
||||
static client: PostHogType | undefined = undefined;
|
||||
static uniqueId = "NOT_UNIQUE";
|
||||
static os: string | undefined = undefined;
|
||||
static ideInfo: IdeInfo | undefined = undefined;
|
||||
|
|
@ -28,6 +46,7 @@ export class Telemetry {
|
|||
distinctId: Telemetry.uniqueId,
|
||||
event,
|
||||
properties: augmentedProperties,
|
||||
sendFeatureFlags: true,
|
||||
};
|
||||
|
||||
// In cases where an extremely early fatal error occurs, we may not have initialized yet
|
||||
|
|
@ -55,7 +74,7 @@ export class Telemetry {
|
|||
Telemetry.client?.shutdown();
|
||||
}
|
||||
|
||||
static async getTelemetryClient() {
|
||||
static async getTelemetryClient(): Promise<PostHogType | undefined> {
|
||||
try {
|
||||
const { PostHog } = await import("posthog-node");
|
||||
return new PostHog("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", {
|
||||
|
|
@ -77,4 +96,21 @@ export class Telemetry {
|
|||
Telemetry.client = await Telemetry.getTelemetryClient();
|
||||
}
|
||||
}
|
||||
|
||||
static async getFeatureFlag(flag: PosthogFeatureFlag) {
|
||||
return Telemetry.client?.getFeatureFlag(flag, Telemetry.uniqueId);
|
||||
}
|
||||
|
||||
static async getValueForFeatureFlag(flag: PosthogFeatureFlag) {
|
||||
try {
|
||||
const userGroup = await Telemetry.getFeatureFlag(flag);
|
||||
if (typeof userGroup === "string") {
|
||||
return EXPERIMENTS[flag][userGroup].value;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -290,7 +290,12 @@ export async function getSymbolsForManyFiles(
|
|||
const filesAndSymbols = await Promise.all(
|
||||
uris.map(async (uri): Promise<[string, SymbolWithRange[]]> => {
|
||||
const contents = await ide.readFile(uri);
|
||||
const symbols = await getSymbolsForFile(uri, contents);
|
||||
let symbols = undefined;
|
||||
try {
|
||||
symbols = await getSymbolsForFile(uri, contents);
|
||||
} catch (e) {
|
||||
console.error(`Failed to get symbols for ${uri}:`, e);
|
||||
}
|
||||
return [uri, symbols ?? []];
|
||||
}),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -495,6 +495,26 @@ Reference the architecture and platform of your current operating system.
|
|||
}
|
||||
```
|
||||
|
||||
### Model Context Protocol
|
||||
|
||||
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this:
|
||||
|
||||
```json
|
||||
{
|
||||
"experimental": {
|
||||
"modelContextProtocolServer": {
|
||||
"transport": {
|
||||
"type": "stdio",
|
||||
"command": "uvx",
|
||||
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
|
||||
|
||||
### `@HTTP`
|
||||
|
||||
The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,67 @@
|
|||
---
|
||||
title: Function Network
|
||||
slug: ../function-network
|
||||
---
|
||||
# Function Network
|
||||
|
||||
> Private, Affordable User-Owned AI
|
||||
|
||||
:::info
|
||||
|
||||
To get an API key, login to the Function Network Developer Platform. If you don't have an account, you can create one [here](https://www.function.network/join-waitlist).
|
||||
|
||||
:::
|
||||
|
||||
## Chat model
|
||||
|
||||
Function Network supports a number of models for chat. We recommend using LLama 3.1 70b or Qwen2.5-Coder-32B-Instruct.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Llama 3.1 70b",
|
||||
"provider": "function-network",
|
||||
"model": "meta/llama-3.1-70b-instruct",
|
||||
"apiKey": "YOUR_API_KEY"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
[Click here](https://docs.function.network/models-supported/chat-and-code-completion) to see a list of chat model providers.
|
||||
|
||||
## Autocomplete model
|
||||
|
||||
Function Network supports a number of models for autocomplete. We recommend using Llama 3.1 8b or Qwen2.5-Coder-1.5B.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "Deepseek Coder 6.7b",
|
||||
"provider": "function-network",
|
||||
"model": "thebloke/deepseek-coder-6.7b-base-awq",
|
||||
"apiKey": "YOUR_API_KEY"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Embeddings model
|
||||
|
||||
Function Network supports a number of models for embeddings. We recommend using baai/bge-base-en-v1.5.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"embeddingsProvider": {
|
||||
"provider": "function-network",
|
||||
"model": "baai/bge-base-en-v1.5",
|
||||
"apiKey": "YOUR_API_KEY"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
[Click here](https://docs.function.network/models-supported/embeddings) to see a list of embeddings model providers.
|
||||
|
||||
## Reranking model
|
||||
|
||||
Function Network currently does not offer any reranking models.
|
||||
|
|
@ -106,3 +106,21 @@ The onboard slash command helps to familiarize yourself with a new project by an
|
|||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Model Context Protocol
|
||||
|
||||
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports MCP "prompts" by creating slash commands. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this:
|
||||
|
||||
```json
|
||||
{
|
||||
"experimental": {
|
||||
"modelContextProtocolServer": {
|
||||
"transport": {
|
||||
"type": "stdio",
|
||||
"command": "uvx",
|
||||
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
|
|||
|
|
@ -435,8 +435,10 @@ class IdeProtocolClient(
|
|||
"getRepoName" -> {
|
||||
// Get the current repository name
|
||||
val dir = (data as Map<String, Any>)["dir"] as String
|
||||
val directory = File(dir)
|
||||
val targetDir = if (directory.isFile) directory.parentFile else directory
|
||||
val builder = ProcessBuilder("git", "config", "--get", "remote.origin.url")
|
||||
builder.directory(File(dir))
|
||||
builder.directory(targetDir)
|
||||
var output = "NONE"
|
||||
try {
|
||||
val process = builder.start()
|
||||
|
|
@ -453,9 +455,10 @@ class IdeProtocolClient(
|
|||
|
||||
"getDiff" -> {
|
||||
val workspaceDirs = workspaceDirectories()
|
||||
val output = StringBuilder()
|
||||
val diffs = mutableListOf<String>()
|
||||
|
||||
for (workspaceDir in workspaceDirs) {
|
||||
val output = StringBuilder()
|
||||
val builder = ProcessBuilder("git", "diff")
|
||||
builder.directory(File(workspaceDir))
|
||||
val process = builder.start()
|
||||
|
|
@ -469,9 +472,10 @@ class IdeProtocolClient(
|
|||
}
|
||||
|
||||
process.waitFor()
|
||||
diffs.add(output.toString())
|
||||
}
|
||||
|
||||
respond(output.toString())
|
||||
respond(diffs)
|
||||
}
|
||||
|
||||
"getProblems" -> {
|
||||
|
|
@ -1091,4 +1095,4 @@ class IdeProtocolClient(
|
|||
|
||||
return matchingModel
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -66,6 +66,7 @@ class ContinueBrowser(val project: Project, url: String) {
|
|||
"config/listProfiles",
|
||||
"profiles/switch",
|
||||
"didChangeSelectedProfile",
|
||||
"context/getSymbolsForFiles",
|
||||
)
|
||||
|
||||
private fun registerAppSchemeHandler() {
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue