From 69453350a20d646b1e97644e8258d5baa4e9b37d Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 21 Aug 2025 13:08:49 -0500 Subject: [PATCH] Add ReadWebpageTool --- package-lock.json | 34 ++++ package.json | 3 + src/lib/tools/ReadWebpageTool.test.ts | 236 ++++++++++++++++++++++++++ src/lib/tools/ReadWebpageTool.ts | 123 ++++++++++++++ 4 files changed, 396 insertions(+) create mode 100644 src/lib/tools/ReadWebpageTool.test.ts create mode 100644 src/lib/tools/ReadWebpageTool.ts diff --git a/package-lock.json b/package-lock.json index 525cbda5..c85d3bf7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "@fontsource-variable/inter": "^5.2.6", "@hookform/resolvers": "^3.9.0", "@isomorphic-git/lightning-fs": "^4.6.2", + "@mozilla/readability": "^0.6.0", "@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4", "@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8", "@radix-ui/react-accordion": "^1.2.0", @@ -75,6 +76,7 @@ "sonner": "^1.5.0", "tailwind-merge": "^2.5.2", "tailwindcss-animate": "^1.0.7", + "turndown": "^7.2.1", "use-stick-to-bottom": "^1.1.1", "vaul": "^0.9.3", "zod": "^3.25.76" @@ -92,6 +94,7 @@ "@types/react": "^18.3.1", "@types/react-dom": "^18.3.1", "@types/react-syntax-highlighter": "^15.5.13", + "@types/turndown": "^5.0.5", "@vitejs/plugin-react-swc": "^3.5.0", "autoprefixer": "^10.4.20", "eslint": "^9.9.0", @@ -1325,6 +1328,21 @@ "resolved": "https://npm.jsr.io/~/11/@jsr/std__internal/1.0.9.tgz", "integrity": "sha512-s+f4qrJzZgPAy7XuFOtgaSaxyPLnnEmAfXGLvRXGxPTL76URLVHkF+hOzqXz+bmk8/awybF6BRsasxtAQOV23Q==" }, + "node_modules/@mixmark-io/domino": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@mixmark-io/domino/-/domino-2.2.0.tgz", + "integrity": "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==", + "license": "BSD-2-Clause" + }, + "node_modules/@mozilla/readability": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@mozilla/readability/-/readability-0.6.0.tgz", + "integrity": "sha512-juG5VWh4qAivzTAeMzvY9xs9HY5rAcr2E4I7tiSSCokRFi7XIZCAu92ZkSTsIj1OPceCifL3cpfteP3pDT9/QQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/@noble/ciphers": { "version": "0.5.3", "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-0.5.3.tgz", @@ -3901,6 +3919,13 @@ "@types/react": "*" } }, + "node_modules/@types/turndown": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@types/turndown/-/turndown-5.0.5.tgz", + "integrity": "sha512-TL2IgGgc7B5j78rIccBtlYAnkuv8nUQqhQc+DSYV5j9Be9XOcm/SKOVRuA47xAVI3680Tk9B1d8flK2GWT2+4w==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/unist": { "version": "2.0.11", "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz", @@ -10805,6 +10830,15 @@ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "license": "0BSD" }, + "node_modules/turndown": { + "version": "7.2.1", + "resolved": "https://registry.npmjs.org/turndown/-/turndown-7.2.1.tgz", + "integrity": "sha512-7YiPJw6rLClQL3oUKN3KgMaXeJJ2lAyZItclgKDurqnH61so4k4IH/qwmMva0zpuJc/FhRExBBnk7EbeFANlgQ==", + "license": "MIT", + "dependencies": { + "@mixmark-io/domino": "^2.2.0" + } + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", diff --git a/package.json b/package.json index 2110d538..cdb4e9d4 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "@fontsource-variable/inter": "^5.2.6", "@hookform/resolvers": "^3.9.0", "@isomorphic-git/lightning-fs": "^4.6.2", + "@mozilla/readability": "^0.6.0", "@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4", "@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8", "@radix-ui/react-accordion": "^1.2.0", @@ -77,6 +78,7 @@ "sonner": "^1.5.0", "tailwind-merge": "^2.5.2", "tailwindcss-animate": "^1.0.7", + "turndown": "^7.2.1", "use-stick-to-bottom": "^1.1.1", "vaul": "^0.9.3", "zod": "^3.25.76" @@ -94,6 +96,7 @@ "@types/react": "^18.3.1", "@types/react-dom": "^18.3.1", "@types/react-syntax-highlighter": "^15.5.13", + "@types/turndown": "^5.0.5", "@vitejs/plugin-react-swc": "^3.5.0", "autoprefixer": "^10.4.20", "eslint": "^9.9.0", diff --git a/src/lib/tools/ReadWebpageTool.test.ts b/src/lib/tools/ReadWebpageTool.test.ts new file mode 100644 index 00000000..de61edf7 --- /dev/null +++ b/src/lib/tools/ReadWebpageTool.test.ts @@ -0,0 +1,236 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { JSDOM } from "jsdom"; +import { ReadWebpageTool } from "./ReadWebpageTool"; + +// Mock fetch globally +const mockFetch = vi.fn(); +global.fetch = mockFetch; + +describe("ReadWebpageTool", () => { + let tool: ReadWebpageTool; + let domParser: DOMParser; + + beforeEach(() => { + // Create a JSDOM instance for testing + const jsdom = new JSDOM(); + domParser = new jsdom.window.DOMParser(); + tool = new ReadWebpageTool(domParser); + mockFetch.mockClear(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("inputSchema", () => { + it("should validate valid URL", () => { + const result = tool.inputSchema.safeParse({ + url: "https://example.com", + }); + expect(result.success).toBe(true); + }); + + it("should reject invalid URL", () => { + const result = tool.inputSchema.safeParse({ + url: "not-a-url", + }); + expect(result.success).toBe(false); + }); + }); + + describe("execute", () => { + it("should extract and convert article content to markdown", async () => { + const mockHtml = ` + + + + Test Article + + +
+

Main Article Title

+

This is the main content of the article.

+

It has multiple paragraphs with bold text and italic text.

+

Subsection

+ +
+ + + + `; + + const mockResponse = { + ok: true, + headers: { + get: vi.fn().mockReturnValue("text/html; charset=utf-8"), + }, + text: vi.fn().mockResolvedValue(mockHtml), + }; + mockFetch.mockResolvedValue(mockResponse); + + const result = await tool.execute({ + url: "https://example.com/article", + }); + + expect(result).toContain("# Test Article"); + expect(result).toContain("**Source:** https://example.com/article"); + expect(result).toContain("Main Article Title"); + expect(result).toContain("**bold text**"); + expect(result).toContain("*italic text*"); + expect(result).toContain("## Subsection"); + expect(result).toContain("* First item"); + expect(result).toContain("* Second item"); + }); + + it("should handle articles with metadata", async () => { + const mockHtml = ` + + + + Article with Metadata + + + + +
+
+

Article with Metadata

+ + +
+

Main article content goes here.

+
+ + + `; + + const mockResponse = { + ok: true, + headers: { + get: vi.fn().mockReturnValue("text/html"), + }, + text: vi.fn().mockResolvedValue(mockHtml), + }; + mockFetch.mockResolvedValue(mockResponse); + + const result = await tool.execute({ + url: "https://example.com/article-with-metadata", + }); + + expect(result).toContain("# Article with Metadata"); + expect(result).toContain("**Source:** https://example.com/article-with-metadata"); + }); + + it("should handle code blocks properly", async () => { + const mockHtml = ` + + + +
+

Code Example

+

Here's some code:

+

+function hello() {
+  console.log("Hello, world!");
+}
+            
+

And some inline code too.

+
+ + + `; + + const mockResponse = { + ok: true, + headers: { + get: vi.fn().mockReturnValue("text/html"), + }, + text: vi.fn().mockResolvedValue(mockHtml), + }; + mockFetch.mockResolvedValue(mockResponse); + + const result = await tool.execute({ + url: "https://example.com/code-example", + }); + + expect(result).toContain("```"); + expect(result).toContain("function hello()"); + expect(result).toContain("`code`"); + }); + + it("should handle HTTP errors", async () => { + const mockResponse = { + ok: false, + status: 404, + statusText: "Not Found", + }; + mockFetch.mockResolvedValue(mockResponse); + + await expect(tool.execute({ + url: "https://example.com/not-found", + })).rejects.toThrow("HTTP 404: Not Found"); + }); + + it("should handle non-HTML content", async () => { + const mockResponse = { + ok: true, + headers: { + get: vi.fn().mockReturnValue("application/json"), + }, + text: vi.fn().mockResolvedValue('{"data": "json"}'), + }; + mockFetch.mockResolvedValue(mockResponse); + + await expect(tool.execute({ + url: "https://api.example.com/data.json", + })).rejects.toThrow("Expected HTML content, but received: application/json"); + }); + + it("should handle network errors", async () => { + mockFetch.mockRejectedValue(new TypeError("Failed to fetch")); + + await expect(tool.execute({ + url: "https://example.com", + })).rejects.toThrow("Network error: Unable to fetch https://example.com"); + }); + + it("should handle pages with minimal content", async () => { + const mockHtml = ` + + + + + + + + `; + + const mockResponse = { + ok: true, + headers: { + get: vi.fn().mockReturnValue("text/html"), + }, + text: vi.fn().mockResolvedValue(mockHtml), + }; + mockFetch.mockResolvedValue(mockResponse); + + const result = await tool.execute({ + url: "https://example.com/minimal-content", + }); + + expect(result).toContain("# Untitled"); + expect(result).toContain("**Source:** https://example.com/minimal-content"); + }); + + it("should handle invalid URLs", async () => { + await expect(tool.execute({ + url: "invalid-url", + })).rejects.toThrow("Failed to read webpage invalid-url"); + }); + }); +}); \ No newline at end of file diff --git a/src/lib/tools/ReadWebpageTool.ts b/src/lib/tools/ReadWebpageTool.ts new file mode 100644 index 00000000..117f7164 --- /dev/null +++ b/src/lib/tools/ReadWebpageTool.ts @@ -0,0 +1,123 @@ +import { Readability } from "@mozilla/readability"; +import TurndownService from "turndown"; +import { z } from "zod"; + +import type { Tool } from "./Tool"; + +interface ReadWebpageParams { + url: string; +} + +export class ReadWebpageTool implements Tool { + private domParser: DOMParser; + private turndownService: TurndownService; + + readonly description = "Read and extract the main content from a webpage, converting it to markdown"; + + readonly inputSchema = z.object({ + url: z.string().url().describe( + "The URL of the webpage to read and extract content from" + ), + }); + + constructor(domParser: DOMParser) { + this.domParser = domParser; + this.turndownService = new TurndownService({ + headingStyle: "atx", + codeBlockStyle: "fenced", + fence: "```", + emDelimiter: "*", + strongDelimiter: "**", + linkStyle: "inlined", + linkReferenceStyle: "full", + }); + + // Configure turndown to preserve code blocks and improve formatting + this.turndownService.addRule("preserveCodeBlocks", { + filter: ["pre"], + replacement: (content, node) => { + const codeElement = node.querySelector("code"); + if (codeElement) { + const language = codeElement.className.match(/language-(\w+)/)?.[1] || ""; + return `\n\n\`\`\`${language}\n${codeElement.textContent || content}\n\`\`\`\n\n`; + } + return `\n\n\`\`\`\n${content}\n\`\`\`\n\n`; + }, + }); + + // Improve table handling + this.turndownService.addRule("tables", { + filter: "table", + replacement: (content) => { + return `\n\n${content}\n\n`; + }, + }); + } + + async execute(args: ReadWebpageParams): Promise { + const { url } = args; + + try { + // Validate URL format + new URL(url); + + // Fetch the webpage + const response = await fetch(url); + + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + + const contentType = response.headers.get("content-type") || ""; + if (!contentType.includes("text/html")) { + throw new Error(`Expected HTML content, but received: ${contentType}`); + } + + const html = await response.text(); + + // Parse the HTML + const doc = this.domParser.parseFromString(html, "text/html"); + + // Use Readability to extract the main content + const reader = new Readability(doc, { + debug: false, + maxElemsToParse: 0, // No limit + nbTopCandidates: 5, + charThreshold: 500, + classesToPreserve: ["highlight", "code", "pre"], + }); + + const article = reader.parse(); + + if (!article) { + throw new Error("Could not extract readable content from the webpage"); + } + + // Convert the extracted HTML content to markdown + const markdown = this.turndownService.turndown(article.content || ""); + + // Create a formatted result with metadata + const result = [ + `# ${article.title || "Untitled"}`, + "", + article.excerpt ? `${article.excerpt}` : "", + article.excerpt ? "" : "", + `**Source:** ${url}`, + article.byline ? `**Author:** ${article.byline}` : "", + article.publishedTime ? `**Published:** ${article.publishedTime}` : "", + "", + "---", + "", + markdown, + ].filter(Boolean).join("\n"); + + return result; + + } catch (error) { + if (error instanceof TypeError && error.message.includes("fetch")) { + throw new Error(`Network error: Unable to fetch ${url}. ${error.message}`); + } + throw new Error(`Failed to read webpage ${url}: ${error instanceof Error ? error.message : String(error)}`); + } + } +} \ No newline at end of file