Elffuss BraidHub

kikocis/continue public

Merge pull request #6439 from continuedev/dallin/limit-web-tool-output

Truncate large agent tool output
Changesetf77b04d889492f21b097da2f84f9af6afcc84d05cfb018a0e9f1bfb55daf4f87
AuthorDallin Romney <dallinromney@gmail.com> · 2025-07-07 12:18 -07:00
CommitterGitHub <noreply@github.com> · 2025-07-07 12:18 -07:00
Parents846ead6f2eaa, bc0f325bd19c

Browse the files at this changeset

8 files changed

modified core/tools/implementations/fetchUrlContent.ts +29 −1
@@ -1,6 +1,34 @@
11 import { ToolImpl } from ".";
22 import { getUrlContextItems } from "../../context/providers/URLContextProvider";
33
4+const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000;
5+
46 export const fetchUrlContentImpl: ToolImpl = async (args, extras) => {
5- return getUrlContextItems(args.url, extras.fetch);
7+ const contextItems = await getUrlContextItems(args.url, extras.fetch);
8+
9+ // Track truncated content
10+ const truncatedUrls: string[] = [];
11+
12+ // Check and truncate each context item
13+ const processedItems = contextItems.map((item) => {
14+ if (item.content.length > DEFAULT_FETCH_URL_CHAR_LIMIT) {
15+ truncatedUrls.push(args.url);
16+ return {
17+ ...item,
18+ content: item.content.substring(0, DEFAULT_FETCH_URL_CHAR_LIMIT),
19+ };
20+ }
21+ return item;
22+ });
23+
24+ // Add truncation warning if needed
25+ if (truncatedUrls.length > 0) {
26+ processedItems.push({
27+ name: "URL content truncation warning",
28+ description: "Informs that URL content was truncated",
29+ content: `The content from ${truncatedUrls.join(", ")} was truncated because it exceeded the ${DEFAULT_FETCH_URL_CHAR_LIMIT} character limit. If you need more content, consider fetching specific sections or using a more targeted approach.`,
30+ });
31+ }
32+
33+ return processedItems;
634 };
added core/tools/implementations/fetchUrlContent.vitest.ts +91 −0
@@ -0,0 +1,91 @@
1+import { expect, test, vi } from "vitest";
2+import { fetchUrlContentImpl } from "./fetchUrlContent";
3+
4+vi.mock("../../context/providers/URLContextProvider", () => ({
5+ getUrlContextItems: vi.fn(),
6+}));
7+
8+import { ToolExtras } from "../..";
9+import { getUrlContextItems } from "../../context/providers/URLContextProvider";
10+const mockExtras = {
11+ fetch: vi.fn() as any,
12+ ide: {} as any,
13+} as unknown as ToolExtras;
14+
15+test("fetchUrlContent should not truncate content under character limit", async () => {
16+ const shortContent = "This is a short content";
17+ const mockContextItems = [
18+ {
19+ name: "Test URL",
20+ description: "Test URL description",
21+ content: shortContent,
22+ },
23+ ];
24+
25+ (getUrlContextItems as any).mockResolvedValue(mockContextItems);
26+
27+ const result = await fetchUrlContentImpl(
28+ { url: "https://example.com" },
29+ mockExtras,
30+ );
31+
32+ expect(result).toHaveLength(1);
33+ expect(result[0].content).toBe(shortContent);
34+});
35+
36+test("fetchUrlContent should truncate content exceeding character limit", async () => {
37+ const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000;
38+ // Create a string exceeding the character limit
39+ const longContent = "a".repeat(DEFAULT_FETCH_URL_CHAR_LIMIT + 1000);
40+ const mockContextItems = [
41+ {
42+ name: "Test URL",
43+ description: "Test URL description",
44+ content: longContent,
45+ },
46+ ];
47+
48+ (getUrlContextItems as any).mockResolvedValue(mockContextItems);
49+
50+ const result = await fetchUrlContentImpl(
51+ { url: "https://example.com" },
52+ mockExtras,
53+ );
54+
55+ expect(result).toHaveLength(2); // Original item + warning
56+ expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
57+ expect(result[1].name).toBe("URL content truncation warning");
58+ expect(result[1].content).toContain("was truncated");
59+ expect(result[1].content).toContain("20000 character limit");
60+});
61+
62+test("fetchUrlContent should add truncation warning with multiple truncated items", async () => {
63+ const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000;
64+ // Create strings exceeding the character limit
65+ const longContent1 = "a".repeat(DEFAULT_FETCH_URL_CHAR_LIMIT + 500);
66+ const longContent2 = "b".repeat(DEFAULT_FETCH_URL_CHAR_LIMIT + 1000);
67+ const mockContextItems = [
68+ {
69+ name: "Test URL 1",
70+ description: "Test URL description 1",
71+ content: longContent1,
72+ },
73+ {
74+ name: "Test URL 2",
75+ description: "Test URL description 2",
76+ content: longContent2,
77+ },
78+ ];
79+
80+ (getUrlContextItems as any).mockResolvedValue(mockContextItems);
81+
82+ const result = await fetchUrlContentImpl(
83+ { url: "https://example.com" },
84+ mockExtras,
85+ );
86+
87+ expect(result).toHaveLength(3); // Two original items + warning
88+ expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
89+ expect(result[1].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
90+ expect(result[2].name).toBe("URL content truncation warning");
91+});
modified core/tools/implementations/lsTool.ts +38 −9
@@ -2,30 +2,59 @@
22 import { walkDir } from "../../indexing/walkDir";
33 import { resolveRelativePathInDir } from "../../util/ideUtils";
44
5+export function resolveLsToolDirPath(dirPath: string | undefined) {
6+ if (!dirPath || dirPath === ".") {
7+ return "/";
8+ }
9+ if (dirPath.startsWith(".")) {
10+ return dirPath.slice(1);
11+ }
12+ return dirPath.replace(/\\/g, "/");
13+}
14+
15+const MAX_LS_TOOL_LINES = 200;
16+
517 export const lsToolImpl: ToolImpl = async (args, extras) => {
6- const uri = await resolveRelativePathInDir(args.dirPath, extras.ide);
18+ const dirPath = resolveLsToolDirPath(args?.dirPath);
19+ const uri = await resolveRelativePathInDir(dirPath, extras.ide);
720 if (!uri) {
821 throw new Error(
9- `Directory ${args.dirPath} not found. Make sure to use forward-slash paths. Do not use e.g. "."`,
22+ `Directory ${args.dirPath} not found. Make sure to use forward-slash paths`,
1023 );
1124 }
1225
1326 const entries = await walkDir(uri, extras.ide, {
1427 returnRelativeUrisPaths: true,
1528 include: "both",
16- recursive: args.recursive ?? false,
29+ recursive: args?.recursive ?? false,
1730 });
1831
19- const content =
20- entries.length > 0
21- ? entries.join("\n")
22- : `No files/folders found in ${args.dirPath}`;
32+ const lines = entries.slice(0, MAX_LS_TOOL_LINES);
2333
24- return [
34+ let content =
35+ lines.length > 0
36+ ? lines.join("\n")
37+ : `No files/folders found in ${dirPath}`;
38+
39+ const contextItems = [
2540 {
2641 name: "File/folder list",
27- description: `Files/folders in ${args.dirPath}`,
42+ description: `Files/folders in ${dirPath}`,
2843 content,
2944 },
3045 ];
46+
47+ if (entries.length > MAX_LS_TOOL_LINES) {
48+ let warningContent = `${entries.length - MAX_LS_TOOL_LINES} ls entries were truncated`;
49+ if (args?.recursive) {
50+ warningContent += ". Try using a non-recursive search";
51+ }
52+ contextItems.push({
53+ name: "ls truncation warning",
54+ description: "Informs the model that ls results were truncated",
55+ content: warningContent,
56+ });
57+ }
58+
59+ return contextItems;
3160 };
added core/tools/implementations/lsTool.vitest.ts +96 −0
@@ -0,0 +1,96 @@
1+import { expect, test, vi } from "vitest";
2+import { ToolExtras } from "../..";
3+import * as walkDirModule from "../../indexing/walkDir";
4+import { lsToolImpl, resolveLsToolDirPath } from "./lsTool";
5+
6+vi.mock("../../indexing/walkDir");
7+
8+const mockExtras = {
9+ ide: {
10+ fileExists: async (path: string) => true,
11+ getWorkspaceDirs: async () => ["dir1"],
12+ },
13+} as unknown as ToolExtras;
14+
15+test("resolveLsToolDirPath handles undefined path", () => {
16+ expect(resolveLsToolDirPath(undefined)).toBe("/");
17+});
18+
19+test("resolveLsToolDirPath handles empty string", () => {
20+ expect(resolveLsToolDirPath("")).toBe("/");
21+});
22+
23+test("resolveLsToolDirPath handles dot", () => {
24+ expect(resolveLsToolDirPath(".")).toBe("/");
25+});
26+
27+test("resolveLsToolDirPath handles dot relative", () => {
28+ expect(resolveLsToolDirPath("./hi")).toBe("/hi");
29+});
30+
31+test("resolveLsToolDirPath normalizes backslashes to forward slashes", () => {
32+ expect(resolveLsToolDirPath("path\\to\\dir")).toBe("path/to/dir");
33+});
34+
35+test("resolveLsToolDirPath preserves forward slashes", () => {
36+ expect(resolveLsToolDirPath("path/to/dir")).toBe("path/to/dir");
37+});
38+
39+test("lsToolImpl truncates output when entries exceed MAX_LS_TOOL_LINES", async () => {
40+ // Generate more than MAX_LS_TOOL_LINES entries (which is 200)
41+ const mockEntries = Array.from({ length: 250 }, (_, i) => `file${i}.txt`);
42+
43+ // Mock walkDir to return our large array
44+ vi.spyOn(walkDirModule, "walkDir").mockResolvedValue(mockEntries);
45+
46+ const result = await lsToolImpl(
47+ { dirPath: "testDir", recursive: true },
48+ mockExtras,
49+ );
50+
51+ // Check that the result contains the truncation message
52+ expect(result.length).toBe(2);
53+ expect(result[0].content).toContain("file1.txt");
54+ expect(result[0].content).toContain("file199.txt");
55+ expect(result[1].content).toContain("Try using a non-recursive search");
56+ expect(result[1].content).toContain("50 ls entries were truncated");
57+
58+ // Check that only MAX_LS_TOOL_LINES entries are included
59+ const contentLines = result[0].content.split("\n");
60+ // Account for the truncation message line
61+ expect(contentLines.length).toBe(200);
62+
63+ // Check the suggestion to use non-recursive search is included
64+ expect(result[1].content).toContain("Try using a non-recursive search");
65+});
66+
67+test("lsToolImpl shows truncation message without suggestion for non-recursive search", async () => {
68+ // Generate more than MAX_LS_TOOL_LINES entries
69+ const mockEntries = Array.from({ length: 250 }, (_, i) => `file${i}.txt`);
70+
71+ // Mock walkDir to return our large array
72+ vi.spyOn(walkDirModule, "walkDir").mockResolvedValue(mockEntries);
73+
74+ const result = await lsToolImpl(
75+ { dirPath: "testDir", recursive: false },
76+ mockExtras,
77+ );
78+
79+ // Check that the result contains the truncation message
80+ expect(result.length).toBe(2);
81+ expect(result[1].content).toContain("50 ls entries were truncated");
82+
83+ // Check that the suggestion to use non-recursive search is NOT included
84+ expect(result[1].content).not.toContain("Try using a non-recursive search");
85+});
86+
87+test("lsToolImpl shows message when no files are found", async () => {
88+ // Mock walkDir to return empty array
89+ vi.spyOn(walkDirModule, "walkDir").mockResolvedValue([]);
90+
91+ const result = await lsToolImpl({ dirPath: "emptyDir" }, mockExtras);
92+
93+ // Check that the result contains the "no files found" message
94+ expect(result.length).toBe(1);
95+ expect(result[0].content).toBe("No files/folders found in emptyDir");
96+});
modified core/tools/implementations/searchWeb.ts +30 −2
@@ -1,8 +1,36 @@
1+import { ToolImpl } from ".";
12 import { fetchSearchResults } from "../../context/providers/WebContextProvider";
23
3-import { ToolImpl } from ".";
4+const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000;
45
56 export const searchWebImpl: ToolImpl = async (args, extras) => {
67 const webResults = await fetchSearchResults(args.query, 5, extras.fetch);
7- return webResults;
8+
9+ // Track truncated results
10+ const truncatedResults: string[] = [];
11+
12+ // Check and truncate each result
13+ const processedResults = webResults.map((result, index) => {
14+ if (result.content.length > DEFAULT_WEB_SEARCH_CHAR_LIMIT) {
15+ truncatedResults.push(
16+ result.name || result.description || `Result #${index + 1}`,
17+ );
18+ return {
19+ ...result,
20+ content: result.content.substring(0, DEFAULT_WEB_SEARCH_CHAR_LIMIT),
21+ };
22+ }
23+ return result;
24+ });
25+
26+ // Add truncation warning if needed
27+ if (truncatedResults.length > 0) {
28+ processedResults.push({
29+ name: "Web search truncation warning",
30+ description: "Informs that search results were truncated",
31+ content: `The content from the following search results was truncated because it exceeded the ${DEFAULT_WEB_SEARCH_CHAR_LIMIT} character limit: ${truncatedResults.join(", ")}. For more detailed information, consider refining your search query.`,
32+ });
33+ }
34+
35+ return processedResults;
836 };
added core/tools/implementations/searchWeb.vitest.ts +107 −0
@@ -0,0 +1,107 @@
1+import { expect, test, vi } from "vitest";
2+import { searchWebImpl } from "./searchWeb";
3+
4+// Mock the fetchSearchResults function
5+vi.mock("../../context/providers/WebContextProvider", () => ({
6+ fetchSearchResults: vi.fn(),
7+}));
8+const mockExtras = {
9+ fetch: vi.fn() as any,
10+ ide: {} as any,
11+} as unknown as ToolExtras;
12+
13+import { ToolExtras } from "../..";
14+import { fetchSearchResults } from "../../context/providers/WebContextProvider";
15+
16+test("searchWeb should not truncate results under character limit", async () => {
17+ const shortContent = "This is a short search result content";
18+ const mockSearchResults = [
19+ {
20+ name: "Result 1",
21+ description: "Search result description 1",
22+ content: shortContent,
23+ },
24+ {
25+ name: "Result 2",
26+ description: "Search result description 2",
27+ content: shortContent,
28+ },
29+ ];
30+
31+ (fetchSearchResults as any).mockResolvedValue(mockSearchResults);
32+
33+ const result = await searchWebImpl({ query: "test query" }, mockExtras);
34+
35+ expect(result).toHaveLength(2);
36+ expect(result[0].content).toBe(shortContent);
37+ expect(result[1].content).toBe(shortContent);
38+});
39+
40+test("searchWeb should truncate results exceeding character limit", async () => {
41+ const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000;
42+ // Create a string exceeding the character limit
43+ const longContent = "a".repeat(DEFAULT_WEB_SEARCH_CHAR_LIMIT + 1000);
44+ const shortContent = "This is a short search result content";
45+ const mockSearchResults = [
46+ {
47+ name: "Result 1",
48+ description: "Search result description 1",
49+ content: longContent,
50+ },
51+ {
52+ name: "Result 2",
53+ description: "Search result description 2",
54+ content: shortContent,
55+ },
56+ ];
57+
58+ (fetchSearchResults as any).mockResolvedValue(mockSearchResults);
59+
60+ const result = await searchWebImpl({ query: "test query" }, mockExtras);
61+
62+ expect(result).toHaveLength(3); // Two results + warning
63+ expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
64+ expect(result[1].content).toBe(shortContent);
65+ expect(result[2].name).toBe("Web search truncation warning");
66+ expect(result[2].content).toContain("truncated");
67+ expect(result[2].content).toContain("Result 1");
68+ expect(result[2].content).not.toContain("Result 2");
69+});
70+
71+test("searchWeb should include all truncated results in the warning", async () => {
72+ const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000;
73+ // Create strings exceeding the character limit
74+ const longContent1 = "a".repeat(DEFAULT_WEB_SEARCH_CHAR_LIMIT + 500);
75+ const longContent2 = "b".repeat(DEFAULT_WEB_SEARCH_CHAR_LIMIT + 1000);
76+ const shortContent = "This is a short search result content";
77+ const mockSearchResults = [
78+ {
79+ name: "Result 1",
80+ description: "Search result description 1",
81+ content: longContent1,
82+ },
83+ {
84+ name: "Result 2",
85+ description: "Search result description 2",
86+ content: longContent2,
87+ },
88+ {
89+ name: "Result 3",
90+ description: "Search result description 3",
91+ content: shortContent,
92+ },
93+ ];
94+
95+ (fetchSearchResults as any).mockResolvedValue(mockSearchResults);
96+
97+ const result = await searchWebImpl({ query: "test query" }, mockExtras);
98+
99+ expect(result).toHaveLength(4); // Three results + warning
100+ expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
101+ expect(result[1].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
102+ expect(result[2].content).toBe(shortContent);
103+ expect(result[3].name).toBe("Web search truncation warning");
104+ expect(result[3].content).toContain("Result 1");
105+ expect(result[3].content).toContain("Result 2");
106+ expect(result[3].content).not.toContain("Result 3");
107+});
modified core/tools/implementations/viewDiff.ts +26 −2
@@ -1,15 +1,39 @@
11 import { ToolImpl } from ".";
2+import { ContextItem } from "../..";
23 import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache";
34
5+export const DEFAULT_GIT_DIFF_LINE_LIMIT = 5000;
6+
47 export const viewDiffImpl: ToolImpl = async (args, extras) => {
58 const diffs = await getDiffsFromCache(extras.ide); // const diffs = await extras.ide.getDiff(true);
69 // TODO includeUnstaged should be an option
710
8- return [
11+ const combinedDiff = diffs.join("\n");
12+ const diffLines = combinedDiff.split("\n");
13+
14+ let truncated = false;
15+ let processedDiff = combinedDiff;
16+
17+ if (diffLines.length > DEFAULT_GIT_DIFF_LINE_LIMIT) {
18+ truncated = true;
19+ processedDiff = diffLines.slice(0, DEFAULT_GIT_DIFF_LINE_LIMIT).join("\n");
20+ }
21+
22+ const contextItems: ContextItem[] = [
923 {
1024 name: "Diff",
1125 description: "The current git diff",
12- content: diffs.join("\n"),
26+ content: processedDiff,
1327 },
1428 ];
29+
30+ if (truncated) {
31+ contextItems.push({
32+ name: "Diff truncation warning",
33+ description: "Informs that git diff was truncated",
34+ content: `The git diff was truncated because it exceeded ${DEFAULT_GIT_DIFF_LINE_LIMIT} lines. Consider viewing specific files or focusing on smaller changes.`,
35+ });
36+ }
37+
38+ return contextItems;
1539 };
added core/tools/implementations/viewDiff.vitest.ts +87 −0
@@ -0,0 +1,87 @@
1+import { expect, test, vi } from "vitest";
2+import { DEFAULT_GIT_DIFF_LINE_LIMIT, viewDiffImpl } from "./viewDiff";
3+
4+// Mock the getDiffsFromCache function
5+vi.mock("../../autocomplete/snippets/gitDiffCache", () => ({
6+ getDiffsFromCache: vi.fn(),
7+}));
8+
9+import { ToolExtras } from "../..";
10+import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache";
11+const mockExtras = {
12+ fetch: vi.fn() as any,
13+ ide: {} as any,
14+} as unknown as ToolExtras;
15+
16+test("viewDiff should not truncate diffs under line limit", async () => {
17+ // Create a small diff with just a few lines
18+ const smallDiff = [
19+ "diff --git a/file1.txt b/file1.txt",
20+ "index 1234..5678 100644",
21+ "--- a/file1.txt",
22+ "+++ b/file1.txt",
23+ "@@ -1,3 +1,4 @@",
24+ " line1",
25+ "-line2",
26+ "+line2 modified",
27+ "+line3 added",
28+ ];
29+
30+ (getDiffsFromCache as any).mockResolvedValue(smallDiff);
31+
32+ const result = await viewDiffImpl({}, mockExtras);
33+
34+ expect(result).toHaveLength(1); // Just the diff, no warning
35+ expect(result[0].name).toBe("Diff");
36+ expect(result[0].content).toBe(smallDiff.join("\n"));
37+});
38+
39+test("viewDiff should truncate diffs exceeding line limit", async () => {
40+ // Create a large diff that exceeds the line limit
41+ const largeDiffLines = Array(DEFAULT_GIT_DIFF_LINE_LIMIT + 1000).fill(
42+ "line content",
43+ );
44+ const largeDiff = [
45+ "diff --git a/file1.txt b/file1.txt",
46+ "index 1234..5678 100644",
47+ ...largeDiffLines,
48+ ];
49+
50+ (getDiffsFromCache as any).mockResolvedValue([largeDiff.join("\n")]);
51+
52+ const result = await viewDiffImpl({}, mockExtras);
53+
54+ expect(result).toHaveLength(2); // Diff + warning
55+
56+ // Count the number of lines in the result
57+ const resultLines = result[0].content.split("\n");
58+ expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT);
59+
60+ // Check the warning
61+ expect(result[1].name).toBe("Diff truncation warning");
62+ expect(result[1].content).toContain("truncated");
63+ expect(result[1].content).toContain(`${DEFAULT_GIT_DIFF_LINE_LIMIT} lines`);
64+});
65+
66+test("viewDiff should handle multiple diffs correctly", async () => {
67+ const DEFAULT_GIT_DIFF_LINE_LIMIT = 5000;
68+
69+ // Create multiple diffs that together exceed the line limit
70+ const diff1Lines = Array(3000).fill("diff1 line");
71+ const diff2Lines = Array(3000).fill("diff2 line");
72+ const diff1 = diff1Lines.join("\n");
73+ const diff2 = diff2Lines.join("\n");
74+
75+ (getDiffsFromCache as any).mockResolvedValue([diff1, diff2]);
76+
77+ const result = await viewDiffImpl({}, mockExtras);
78+
79+ expect(result).toHaveLength(2); // Diff + warning
80+
81+ // Count the number of lines in the result
82+ const resultLines = result[0].content.split("\n");
83+ expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT);
84+
85+ // Check the warning
86+ expect(result[1].name).toBe("Diff truncation warning");
87+});