feat: cli fetch tool to use fetchUrlContent from core
This commit is contained in:
parent
069c033ad6
commit
c8b7ccfad4
3 changed files with 203 additions and 100 deletions
169
extensions/cli/src/tools/fetch.test.ts
Normal file
169
extensions/cli/src/tools/fetch.test.ts
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
import type { ContextItem } from "core/index.js";
|
||||
import { fetchUrlContentImpl } from "core/tools/implementations/fetchUrlContent.js";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { fetchTool } from "./fetch.js";
|
||||
|
||||
// Mock the core fetchUrlContent implementation
|
||||
vi.mock("core/tools/implementations/fetchUrlContent.js", () => ({
|
||||
fetchUrlContentImpl: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockFetchUrlContentImpl = vi.mocked(fetchUrlContentImpl);
|
||||
|
||||
describe("fetchTool", () => {
|
||||
let originalConsoleError: typeof console.error;
|
||||
|
||||
beforeEach(() => {
|
||||
originalConsoleError = console.error;
|
||||
console.error = vi.fn();
|
||||
mockFetchUrlContentImpl.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
console.error = originalConsoleError;
|
||||
});
|
||||
|
||||
it("should return clean content from successful fetch", async () => {
|
||||
const mockContextItems: ContextItem[] = [
|
||||
{
|
||||
name: "Example Page",
|
||||
description: "https://example.com",
|
||||
content:
|
||||
"# Example Page\n\nThis is some example content from a webpage.",
|
||||
uri: { type: "url", value: "https://example.com" },
|
||||
},
|
||||
];
|
||||
|
||||
mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
|
||||
|
||||
const result = await fetchTool.run({ url: "https://example.com" });
|
||||
|
||||
expect(result).toBe(
|
||||
"# Example Page\n\nThis is some example content from a webpage.",
|
||||
);
|
||||
expect(mockFetchUrlContentImpl).toHaveBeenCalledWith(
|
||||
{ url: "https://example.com" },
|
||||
{ fetch },
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle truncation warnings from core implementation", async () => {
|
||||
const mockContextItems: ContextItem[] = [
|
||||
{
|
||||
name: "Long Page",
|
||||
description: "https://example.com",
|
||||
content: "This is the main content that was truncated.",
|
||||
uri: { type: "url", value: "https://example.com" },
|
||||
},
|
||||
{
|
||||
name: "Truncation warning",
|
||||
description: "",
|
||||
content:
|
||||
"The content from https://example.com was truncated because it exceeded the 20000 character limit.",
|
||||
},
|
||||
];
|
||||
|
||||
mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
|
||||
|
||||
const result = await fetchTool.run({ url: "https://example.com" });
|
||||
|
||||
expect(result).toBe(
|
||||
"This is the main content that was truncated.\n\nThe content from https://example.com was truncated because it exceeded the 20000 character limit.",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle multiple content items", async () => {
|
||||
const mockContextItems: ContextItem[] = [
|
||||
{
|
||||
name: "Page 1",
|
||||
description: "https://example.com",
|
||||
content: "Content from page 1",
|
||||
uri: { type: "url", value: "https://example.com" },
|
||||
},
|
||||
{
|
||||
name: "Page 2",
|
||||
description: "https://example.com",
|
||||
content: "Content from page 2",
|
||||
uri: { type: "url", value: "https://example.com" },
|
||||
},
|
||||
];
|
||||
|
||||
mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
|
||||
|
||||
const result = await fetchTool.run({ url: "https://example.com" });
|
||||
|
||||
expect(result).toBe("Content from page 1\n\nContent from page 2");
|
||||
});
|
||||
|
||||
it("should return error message when no content items returned", async () => {
|
||||
mockFetchUrlContentImpl.mockResolvedValue([]);
|
||||
|
||||
const result = await fetchTool.run({ url: "https://example.com" });
|
||||
|
||||
expect(result).toBe(
|
||||
"Error: Could not fetch content from https://example.com",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle errors from core implementation", async () => {
|
||||
const error = new Error("Network error");
|
||||
mockFetchUrlContentImpl.mockRejectedValue(error);
|
||||
|
||||
const result = await fetchTool.run({ url: "https://example.com" });
|
||||
|
||||
expect(result).toBe("Error: Network error");
|
||||
});
|
||||
|
||||
it("should call fetchUrlContentImpl with correct arguments", async () => {
|
||||
const mockContextItems: ContextItem[] = [
|
||||
{
|
||||
name: "Test Page",
|
||||
description: "https://example.com",
|
||||
content: "Test content",
|
||||
uri: { type: "url", value: "https://example.com" },
|
||||
},
|
||||
];
|
||||
|
||||
mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
|
||||
|
||||
await fetchTool.run({ url: "https://example.com" });
|
||||
|
||||
expect(mockFetchUrlContentImpl).toHaveBeenCalledWith(
|
||||
{ url: "https://example.com" },
|
||||
{ fetch },
|
||||
);
|
||||
});
|
||||
|
||||
it("should have correct tool metadata", () => {
|
||||
expect(fetchTool.name).toBe("Fetch");
|
||||
expect(fetchTool.displayName).toBe("Fetch");
|
||||
expect(fetchTool.description).toBe(
|
||||
"Fetches content from a URL, converts to markdown, and handles long content with truncation",
|
||||
);
|
||||
expect(fetchTool.readonly).toBe(true);
|
||||
expect(fetchTool.isBuiltIn).toBe(true);
|
||||
expect(fetchTool.parameters).toEqual({
|
||||
url: {
|
||||
type: "string",
|
||||
description: "The URL to fetch content from",
|
||||
required: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should provide correct preview in preprocess", async () => {
|
||||
const args = { url: "https://example.com" };
|
||||
const result = await fetchTool.preprocess?.(args);
|
||||
|
||||
expect(result).toEqual({
|
||||
preview: [
|
||||
{
|
||||
type: "text",
|
||||
content: "Will fetch: https://example.com",
|
||||
},
|
||||
],
|
||||
args,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,50 +1,19 @@
|
|||
import TurndownService from "turndown";
|
||||
import type { ContextItem } from "core/index.js";
|
||||
import { fetchUrlContentImpl } from "core/tools/implementations/fetchUrlContent.js";
|
||||
|
||||
import { Tool } from "./types.js";
|
||||
|
||||
const turndownService = new TurndownService({
|
||||
headingStyle: "atx",
|
||||
codeBlockStyle: "fenced",
|
||||
fence: "```",
|
||||
emDelimiter: "*",
|
||||
strongDelimiter: "**",
|
||||
linkStyle: "inlined",
|
||||
linkReferenceStyle: "full",
|
||||
});
|
||||
|
||||
// Configure turndown for better markdown output
|
||||
turndownService.addRule("strikethrough", {
|
||||
filter: ["del", "s"],
|
||||
replacement: function (content) {
|
||||
return "~~" + content + "~~";
|
||||
},
|
||||
});
|
||||
|
||||
// Handle code blocks better
|
||||
turndownService.addRule("pre", {
|
||||
filter: "pre",
|
||||
replacement: function (content, node) {
|
||||
const codeEl = node.querySelector("code");
|
||||
const language = codeEl?.className.match(/language-(\w+)/)?.[1] || "";
|
||||
return "\n\n```" + language + "\n" + content + "\n```\n\n";
|
||||
},
|
||||
});
|
||||
|
||||
export const fetchTool: Tool = {
|
||||
name: "Fetch",
|
||||
displayName: "Fetch",
|
||||
description: "Fetches content from a URL and converts it to markdown format",
|
||||
description:
|
||||
"Fetches content from a URL, converts to markdown, and handles long content with truncation",
|
||||
parameters: {
|
||||
url: {
|
||||
type: "string",
|
||||
description: "The URL to fetch content from",
|
||||
required: true,
|
||||
},
|
||||
timeout: {
|
||||
type: "number",
|
||||
description: "Request timeout in milliseconds (default: 10000)",
|
||||
required: false,
|
||||
},
|
||||
},
|
||||
readonly: true,
|
||||
isBuiltIn: true,
|
||||
|
|
@ -59,76 +28,34 @@ export const fetchTool: Tool = {
|
|||
args,
|
||||
};
|
||||
},
|
||||
run: async (args: { url: string; timeout?: number }): Promise<string> => {
|
||||
const { url, timeout = 10000 } = args;
|
||||
run: async (args: { url: string }): Promise<string> => {
|
||||
const { url } = args;
|
||||
|
||||
try {
|
||||
// Validate URL
|
||||
const urlObj = new URL(url);
|
||||
if (!["http:", "https:"].includes(urlObj.protocol)) {
|
||||
return "Error: Only HTTP and HTTPS URLs are supported";
|
||||
// Suppress console errors from JSDOM CSS parsing
|
||||
const originalConsoleError = console.error;
|
||||
console.error = () => {};
|
||||
|
||||
// Use the core fetchUrlContent implementation
|
||||
const contextItems = await fetchUrlContentImpl({ url }, { fetch });
|
||||
|
||||
// Restore console.error
|
||||
console.error = originalConsoleError;
|
||||
|
||||
if (contextItems.length === 0) {
|
||||
return `Error: Could not fetch content from ${url}`;
|
||||
}
|
||||
|
||||
// Fetch the content
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
||||
|
||||
const response = await fetch(url, {
|
||||
signal: controller.signal,
|
||||
headers: {
|
||||
"User-Agent": "Continue-CLI/1.0 (https://continue.dev)",
|
||||
Accept:
|
||||
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||
"Accept-Language": "en-US,en;q=0.5",
|
||||
"Accept-Encoding": "gzip, deflate",
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (!response.ok) {
|
||||
return `Error: HTTP ${response.status} - ${response.statusText}`;
|
||||
}
|
||||
|
||||
const contentType = response.headers.get("content-type") || "";
|
||||
|
||||
// Handle different content types
|
||||
if (contentType.includes("application/json")) {
|
||||
const json = await response.json();
|
||||
return "```json\n" + JSON.stringify(json, null, 2) + "\n```";
|
||||
}
|
||||
|
||||
if (contentType.includes("text/plain")) {
|
||||
const text = await response.text();
|
||||
return text;
|
||||
}
|
||||
|
||||
if (!contentType.includes("text/html")) {
|
||||
return `Error: Unsupported content type: ${contentType}`;
|
||||
}
|
||||
|
||||
// Process HTML content
|
||||
const html = await response.text();
|
||||
|
||||
// Convert HTML to markdown
|
||||
const markdown = turndownService.turndown(html);
|
||||
|
||||
// Clean up the markdown
|
||||
const cleanedMarkdown = markdown
|
||||
.replace(/\n\s*\n\s*\n/g, "\n\n") // Remove excessive newlines
|
||||
.replace(/^\s+|\s+$/g, "") // Trim whitespace
|
||||
.replace(/\\\[/g, "[") // Unescape brackets
|
||||
.replace(/\\\]/g, "]");
|
||||
|
||||
return `# Content from ${url}\n\n${cleanedMarkdown}`;
|
||||
// Format the results for CLI display
|
||||
return contextItems
|
||||
.map((item: ContextItem) => {
|
||||
if (item.name === "Truncation warning") {
|
||||
return item.content;
|
||||
}
|
||||
return item.content;
|
||||
})
|
||||
.join("\n\n");
|
||||
} catch (error) {
|
||||
if (error instanceof TypeError && error.message.includes("fetch")) {
|
||||
return `Error: Failed to fetch URL "${url}". Please check the URL and try again.`;
|
||||
}
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
return `Error: Request timed out after ${timeout}ms`;
|
||||
}
|
||||
return `Error: ${error instanceof Error ? error.message : String(error)}`;
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -13,6 +13,13 @@ vi.mock("../../index.js", () => ({
|
|||
setExitMessageCallback: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock git utility functions
|
||||
vi.mock("../../util/git.js", () => ({
|
||||
isGitRepo: vi.fn(() => false),
|
||||
getGitRemoteUrl: vi.fn(() => null),
|
||||
getGitBranch: vi.fn(() => null),
|
||||
}));
|
||||
|
||||
describe("BottomStatusBar Ctrl+C message", () => {
|
||||
const defaultProps: BottomStatusBarProps = {
|
||||
currentMode: "normal" as const,
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue