Skip to content

Open source CapCut alternative.

TypeScript

feat(app): read web pages as clean markdown via the backend

David Lea6d6670e7321
diff --git a/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift
index 560ba077..bbce41f0 100644
--- a/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift
+++ b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift
@@ -78,15 +78,16 @@ final class GeminiLiveVoiceController {
// Wire the generic LLM tool into the fast path too, so the Live model can compose/transform
// text mid-task (a tracklist, a clean note body) through the hosted route.
var services = HarnessBuiltInToolServices(commandExecutor: DonkeyCommandBackends.makeExecutor())
- let webTools = WebTools()
- services.webFetcher = { await webTools.fetch($0) }
if let backendConfiguration = try? DonkeyBackendInferenceConfiguration.fromEnvironment() {
let backend = DonkeyBackendInferenceClient(configuration: backendConfiguration)
let textGenerator = HostedTextGenerator(backend: backend)
services.textGenerator = { await textGenerator.generate($0) }
- // Search goes through the backend (service-account Google Search grounding).
+ // Web research goes through the backend on the service-account credential: search uses
+ // Google Search grounding; fetch returns the page as clean markdown (boilerplate stripped).
let hostedWebSearch = HostedWebSearch(backend: backend)
services.webSearcher = { await hostedWebSearch.search($0) }
+ let hostedWebFetch = HostedWebFetch(backend: backend)
+ services.webFetcher = { await hostedWebFetch.fetch($0) }
}
let extraToolNames: Set<String> = ["llm.generate", "web.search", "web.fetch"]
let extraDescriptors = BuiltInHarnessToolCatalog.descriptors.filter { extraToolNames.contains($0.name) }
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index a4fc3b37..367534cd 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -351,12 +351,13 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
harnessServices.textGenerator = { prompt in
await textGenerator.generate(prompt)
}
- // Web research: search goes through the backend (Google Search grounding on the
- // service-account credential — no key in the app); fetch reads a page directly.
+ // Web research goes through the backend on the service-account credential — no key in the
+ // app. Search uses Google Search grounding; fetch reads a page and returns clean markdown
+ // (nav/ads/boilerplate stripped server-side) so the model gets the article, not raw HTML.
let hostedWebSearch = HostedWebSearch(backend: backend)
- let webTools = WebTools()
+ let hostedWebFetch = HostedWebFetch(backend: backend)
harnessServices.webSearcher = { query in await hostedWebSearch.search(query) }
- harnessServices.webFetcher = { url in await webTools.fetch(url) }
+ harnessServices.webFetcher = { url in await hostedWebFetch.fetch(url) }
let granted = Self.userQueryGrantedPermissions
let replacedBuiltIns: Set<String> = ["screen.observe", "elements.get", "element.perform", "text.enter", "keyboard.press"]
let builtInDescriptors = BuiltInHarnessToolCatalog.descriptors.filter { descriptor in
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift
index d066773a..7e730a98 100644
--- a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift
+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift
@@ -161,6 +161,18 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {
return try JSONDecoder().decode(RemoteWebSearchResult.self, from: data)
}
+ /// Read a web page through the backend's reader (SSRF-guarded, fetch + cleanup run server-side).
+ /// Returns just the main content as clean markdown — nav/ads/boilerplate stripped — plus the title.
+ public func fetchWeb(url: String) async throws -> RemoteWebFetchResult {
+ var request = makeRequest(path: "/api/web/fetch/")
+ request.httpMethod = "POST"
+ // The backend caps its own fetch at 20s; give the round trip a little headroom over that.
+ request.timeoutInterval = 30
+ request.httpBody = try JSONEncoder().encode(["url": url])
+ let data = try await send(request)
+ return try JSONDecoder().decode(RemoteWebFetchResult.self, from: data)
+ }
+
public func parseScreenshot(
_ understandingRequest: LocalUIUnderstandingRequest,
imageData: Data? = nil,
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedWebFetch.swift b/apps/Donkey/Sources/DonkeyAI/HostedWebFetch.swift
new file mode 100644
index 00000000..1fd8a3d6
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/HostedWebFetch.swift
@@ -0,0 +1,72 @@
+import DonkeyContracts
+import DonkeyHarness
+import Foundation
+
+/// The backend's web-page reader response: the page's main content as clean markdown plus its title.
+public struct RemoteWebFetchResult: Codable, Sendable {
+ public var title: String
+ public var markdown: String
+ public var author: String?
+ public var published: String?
+ public var wordCount: Int?
+
+ public init(
+ title: String,
+ markdown: String,
+ author: String? = nil,
+ published: String? = nil,
+ wordCount: Int? = nil
+ ) {
+ self.title = title
+ self.markdown = markdown
+ self.author = author
+ self.published = published
+ self.wordCount = wordCount
+ }
+}
+
+/// Backs the `web.fetch` harness tool by calling the Donkey backend's reader endpoint, where the
+/// fetch and HTML→markdown cleanup run server-side. Returns a single text block — a title line, any
+/// byline/date, then the article as markdown — for the agent to read, summarize, or save into a note.
+public struct HostedWebFetch: Sendable {
+ private let backend: DonkeyBackendInferenceClient
+ private let timeoutSeconds: TimeInterval
+
+ public init(backend: DonkeyBackendInferenceClient, timeoutSeconds: TimeInterval = 30) {
+ self.backend = backend
+ self.timeoutSeconds = timeoutSeconds
+ }
+
+ public func fetch(_ url: String) async -> String? {
+ let backend = self.backend
+ guard let result = try? await AIDeadline.enforce(seconds: timeoutSeconds, {
+ try await backend.fetchWeb(url: url)
+ }) else {
+ return nil
+ }
+ let markdown = result.markdown.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !markdown.isEmpty else {
+ return nil
+ }
+ var lines: [String] = []
+ let title = result.title.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !title.isEmpty {
+ lines.append("# \(title)")
+ }
+ var byline: [String] = []
+ if let author = result.author?.trimmingCharacters(in: .whitespacesAndNewlines), !author.isEmpty {
+ byline.append(author)
+ }
+ if let published = result.published?.trimmingCharacters(in: .whitespacesAndNewlines), !published.isEmpty {
+ byline.append(published)
+ }
+ if !byline.isEmpty {
+ lines.append("_\(byline.joined(separator: " · "))_")
+ }
+ if !lines.isEmpty {
+ lines.append("")
+ }
+ lines.append(markdown)
+ return lines.joined(separator: "\n")
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
index c053d6e7..c671926b 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
@@ -517,13 +517,13 @@ public enum BuiltInHarnessToolCatalog {
descriptor(
"web.fetch",
pluginID: "core.web",
- summary: "Fetch a web page and return its readable text (HTML stripped). Use it to read a page from web.search or a URL the user gave. Set toFile=true for a long page so you build a note/document from the file instead of a length-limited command.",
+ summary: "Read a web page and return its main content as clean markdown — nav, ads, and boilerplate removed, with the title, headings, links, and lists kept. Use it to read a page from web.search or a URL the user gave. Set toFile=true for a long page so you build a note/document from the file instead of a length-limited command.",
input: [
"url": "The page URL to read.",
- "toFile": "\"true\" to write the page text to a temp file and return its path."
+ "toFile": "\"true\" to write the page content to a temp file and return its path."
],
output: [
- "text": "The page's readable text (a preview when written to a file).",
+ "text": "The page's main content as markdown (a preview when written to a file).",
"filePath": "Path to the file holding the full text, when toFile=true."
],
permissions: [],
diff --git a/apps/Donkey/Sources/DonkeyRuntime/WebTools.swift b/apps/Donkey/Sources/DonkeyRuntime/WebTools.swift
deleted file mode 100644
index 3f4d6e7c..00000000
--- a/apps/Donkey/Sources/DonkeyRuntime/WebTools.swift
+++ /dev/null
@@ -1,90 +0,0 @@
-import Foundation
-
-/// Concrete web capabilities behind the `web.search` and `web.fetch` harness tools: a Google
-/// Programmable Search query and a plain HTTP page read. Both return readable text the planner can
-/// use as evidence (find a current fact, then read the page). Network egress, so they are read-only
-/// and never run state-changing requests.
-public struct WebTools: Sendable {
- private let apiKey: String?
- private let searchEngineID: String?
- private let session: URLSession
-
- /// Credentials come from the environment so no key is compiled into the app:
- /// `GOOGLE_SEARCH_API_KEY` and `GOOGLE_SEARCH_ENGINE_ID` (the Programmable Search Engine `cx`).
- public init(environment: [String: String] = ProcessInfo.processInfo.environment, session: URLSession = .shared) {
- self.apiKey = environment["GOOGLE_SEARCH_API_KEY"].flatMap { $0.isEmpty ? nil : $0 }
- self.searchEngineID = environment["GOOGLE_SEARCH_ENGINE_ID"].flatMap { $0.isEmpty ? nil : $0 }
- self.session = session
- }
-
- public var isSearchConfigured: Bool { apiKey != nil && searchEngineID != nil }
-
- /// Google Programmable Search: returns up to `count` results as "title — url\nsnippet" blocks.
- public func search(_ query: String, count: Int = 5) async -> String? {
- guard let apiKey, let searchEngineID else { return nil }
- var components = URLComponents(string: "https://www.googleapis.com/customsearch/v1")
- components?.queryItems = [
- URLQueryItem(name: "key", value: apiKey),
- URLQueryItem(name: "cx", value: searchEngineID),
- URLQueryItem(name: "q", value: query),
- URLQueryItem(name: "num", value: String(min(max(count, 1), 10)))
- ]
- guard let url = components?.url else { return nil }
- guard let (data, response) = try? await session.data(from: url),
- (response as? HTTPURLResponse)?.statusCode == 200 else {
- return nil
- }
- guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
- let items = root["items"] as? [[String: Any]] else {
- return nil
- }
- let blocks = items.compactMap { item -> String? in
- let title = (item["title"] as? String) ?? ""
- let link = (item["link"] as? String) ?? ""
- let snippet = (item["snippet"] as? String) ?? ""
- guard !title.isEmpty || !link.isEmpty else { return nil }
- return "\(title) — \(link)\n\(snippet)"
- }
- return blocks.isEmpty ? nil : blocks.joined(separator: "\n\n")
- }
-
- /// Fetch a URL and return its readable text (tags and scripts stripped, whitespace collapsed).
- public func fetch(_ urlString: String) async -> String? {
- guard let url = URL(string: urlString), url.scheme?.hasPrefix("http") == true else { return nil }
- var request = URLRequest(url: url)
- request.setValue("Mozilla/5.0 (Macintosh) Donkey/1.0", forHTTPHeaderField: "User-Agent")
- request.timeoutInterval = 20
- guard let (data, response) = try? await session.data(for: request),
- (response as? HTTPURLResponse)?.statusCode == 200,
- let html = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1) else {
- return nil
- }
- return Self.readableText(fromHTML: html)
- }
-
- /// Strip script/style blocks and HTML tags to readable text. Deliberately simple (no DOM): good
- /// enough to give the model the page's words without pulling in a parser dependency.
- public static func readableText(fromHTML html: String) -> String {
- var text = html
- for pattern in ["<script[\\s\\S]*?</script>", "<style[\\s\\S]*?</style>", "<!--[\\s\\S]*?-->"] {
- text = text.replacingOccurrences(of: pattern, with: " ", options: [.regularExpression, .caseInsensitive])
- }
- // Turn block-level closes into newlines so paragraphs survive, then drop remaining tags.
- text = text.replacingOccurrences(of: "</(p|div|li|h[1-6]|br|tr)>", with: "\n", options: [.regularExpression, .caseInsensitive])
- text = text.replacingOccurrences(of: "<[^>]+>", with: " ", options: .regularExpression)
- text = decodeEntities(text)
- // Collapse runs of whitespace, keeping line breaks.
- text = text.replacingOccurrences(of: "[ \\t\\x0B\\f\\r]+", with: " ", options: .regularExpression)
- text = text.replacingOccurrences(of: "\\n\\s*\\n\\s*\\n+", with: "\n\n", options: .regularExpression)
- return text.trimmingCharacters(in: .whitespacesAndNewlines)
- }
-
- private static func decodeEntities(_ text: String) -> String {
- var result = text
- let entities = ["&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": "\"", "&#39;": "'", "&apos;": "'", "&nbsp;": " "]
- for (entity, value) in entities {
- result = result.replacingOccurrences(of: entity, with: value)
- }
- return result
- }
-}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
index 69d15c1e..1e9d3b15 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
@@ -287,17 +287,6 @@ struct GenericHarnessTests {
#expect(search.metadata["reason"] == "webSearchUnavailable")
}
- @Test
- func htmlIsStrippedToReadableText() {
- let html = "<html><head><style>.x{}</style><script>bad()</script></head><body><h1>Title</h1><p>First &amp; second.</p><p>Third</p></body></html>"
- let text = WebTools.readableText(fromHTML: html)
- #expect(text.contains("Title"))
- #expect(text.contains("First & second."))
- #expect(text.contains("Third"))
- #expect(!text.contains("bad()"))
- #expect(!text.contains("<"))
- }
-
@Test
func llmGenerateFailsCleanlyWithoutAModelBoundary() async {
let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()