Skip to content

Open source CapCut alternative.

TypeScript

feat(app): web.search and web.fetch tools for current-fact research

David Le098bdd2e07b2
diff --git a/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift
index dccbd037..2edee9df 100644
--- a/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift
+++ b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift
@@ -84,8 +84,12 @@ final class GeminiLiveVoiceController {
)
services.textGenerator = { await textGenerator.generate($0) }
}
- let llmDescriptors = BuiltInHarnessToolCatalog.descriptors.filter { $0.name == "llm.generate" }
- let liveDescriptors = DonkeyCommandLayer.descriptors + llmDescriptors
+ let webTools = WebTools()
+ services.webSearcher = { await webTools.search($0) }
+ services.webFetcher = { await webTools.fetch($0) }
+ let extraToolNames: Set<String> = ["llm.generate", "web.search", "web.fetch"]
+ let extraDescriptors = BuiltInHarnessToolCatalog.descriptors.filter { extraToolNames.contains($0.name) }
+ let liveDescriptors = DonkeyCommandLayer.descriptors + extraDescriptors
self.liveToolDescriptors = liveDescriptors
self.registry = HarnessToolRegistry(
tools: BuiltInHarnessToolExecutors.tools(
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index 4ccbb7ee..095a51fd 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -351,6 +351,11 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
harnessServices.textGenerator = { prompt in
await textGenerator.generate(prompt)
}
+ // Web research: find current facts and read pages (e.g. an artist's latest album, then its
+ // tracklist), so tasks needing fresh information aren't stuck guessing.
+ let webTools = WebTools()
+ harnessServices.webSearcher = { query in await webTools.search(query) }
+ harnessServices.webFetcher = { url in await webTools.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/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
index 5e489787..7dc2bf3b 100644
--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
@@ -196,6 +196,11 @@ public enum DonkeyPrompts {
- Driving a specific app with no operating guide above? Look its skill up first (app_skill, or
skill.search for workflows) — the installed skill is the authority on how that app is
operated and overrides assumptions.
+ - Need a current fact you can't be sure of (an artist's latest album, today's news, a price, an
+ address)? Use web.search to find it and web.fetch to read a result in full — don't guess and
+ don't drive a browser GUI for this. To build a long note/document (a tracklist, lyrics, a
+ summary), generate it with llm.generate (or fetch it) using toFile=true, then assemble the
+ note from the returned file — never refuse a task as "too long".
- If the request is a question or chit-chat rather than an action, answer with
conversation.respond (set input.response), then run.complete.
- If a required detail is missing and you cannot safely proceed, use user.clarify
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
index ff7286aa..e85db491 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
@@ -195,6 +195,12 @@ public struct HarnessBuiltInToolServices: Sendable {
/// failure). Backs the `llm.generate` tool, the model boundary the planner can reach for to
/// compose, transform, summarize, or massage text without leaving the harness.
public var textGenerator: (@Sendable (String) async -> String?)?
+ /// Web search: a query in, ranked results as text (title — url, then snippet, per result), or nil
+ /// on failure. Backs the `web.search` tool so the agent can find current facts.
+ public var webSearcher: (@Sendable (String) async -> String?)?
+ /// Web fetch/navigation: a URL in, the page's readable text out, or nil on failure. Backs the
+ /// `web.fetch` tool so the agent can read a page it found or was given.
+ public var webFetcher: (@Sendable (String) async -> String?)?
public init(
memoryEntries: [HarnessMemoryEntry] = [],
@@ -206,7 +212,9 @@ public struct HarnessBuiltInToolServices: Sendable {
appleScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil,
skillScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil,
commandExecutor: (@Sendable (HarnessToolExecutionContext) async -> HarnessToolResult?)? = nil,
- textGenerator: (@Sendable (String) async -> String?)? = nil
+ textGenerator: (@Sendable (String) async -> String?)? = nil,
+ webSearcher: (@Sendable (String) async -> String?)? = nil,
+ webFetcher: (@Sendable (String) async -> String?)? = nil
) {
self.memoryEntries = memoryEntries
self.skillRegistry = skillRegistry
@@ -218,6 +226,8 @@ public struct HarnessBuiltInToolServices: Sendable {
self.skillScriptExecutor = skillScriptExecutor
self.commandExecutor = commandExecutor
self.textGenerator = textGenerator
+ self.webSearcher = webSearcher
+ self.webFetcher = webFetcher
}
}
@@ -290,6 +300,10 @@ public enum BuiltInHarnessToolExecutors {
return stateVerify(context)
case "llm.generate":
return await llmGenerate(context, services: services)
+ case "web.search":
+ return await webSearch(context, services: services)
+ case "web.fetch":
+ return await webFetch(context, services: services)
case "wait":
return await timingWait(context)
case "run.pause", "run.resume", "run.recover", "run.cancel", "run.complete", "run.failSafe":
@@ -1288,6 +1302,63 @@ public enum BuiltInHarnessToolExecutors {
)
}
+ private static func webSearch(
+ _ context: HarnessToolExecutionContext,
+ services: HarnessBuiltInToolServices
+ ) async -> HarnessToolResult {
+ guard let searcher = services.webSearcher else {
+ return failed(context, "Web search is not configured.", reason: "webSearchUnavailable")
+ }
+ guard let query = trimmed(context.call.input["query"]) else {
+ return invalidInput(context, "web.search requires a `query`.")
+ }
+ guard let results = await searcher(query), !results.isEmpty else {
+ return failed(context, "No results for \"\(query)\".", reason: "noWebResults")
+ }
+ return success(
+ context,
+ summary: results.count > 600 ? String(results.prefix(600)) + "…" : results,
+ facts: ["lastAcceptedTool": context.call.name],
+ metadata: ["results": results, "query": query]
+ )
+ }
+
+ private static func webFetch(
+ _ context: HarnessToolExecutionContext,
+ services: HarnessBuiltInToolServices
+ ) async -> HarnessToolResult {
+ guard let fetcher = services.webFetcher else {
+ return failed(context, "Web fetch is not configured.", reason: "webFetchUnavailable")
+ }
+ guard let url = trimmed(context.call.input["url"]) else {
+ return invalidInput(context, "web.fetch requires a `url`.")
+ }
+ guard let text = await fetcher(url), !text.isEmpty else {
+ return failed(context, "Could not read \(url).", reason: "webFetchFailed")
+ }
+ if (context.call.input["toFile"] ?? "").lowercased() == "true" {
+ let fileURL = FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-web-\(context.call.id).txt")
+ do {
+ try text.write(to: fileURL, atomically: true, encoding: .utf8)
+ } catch {
+ return failed(context, "Could not write page text to a file: \(error)", reason: "fileWriteFailed")
+ }
+ return success(
+ context,
+ summary: "Fetched \(text.count) characters → \(fileURL.path)",
+ facts: ["lastAcceptedTool": context.call.name],
+ metadata: ["filePath": fileURL.path, "text": String(text.prefix(200)), "characterCount": String(text.count)]
+ )
+ }
+ return success(
+ context,
+ summary: text.count > 600 ? String(text.prefix(600)) + "…" : text,
+ facts: ["lastAcceptedTool": context.call.name],
+ metadata: ["text": text, "characterCount": String(text.count)]
+ )
+ }
+
private static func timingWait(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {
let requested = context.call.input["seconds"].flatMap(Double.init) ?? 1
let seconds = min(max(requested, 0.1), 10)
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
index 97f2df14..c053d6e7 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
@@ -503,6 +503,34 @@ public enum BuiltInHarnessToolCatalog {
verification: ["the returned text (or file) contains the requested content"],
metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]
),
+ descriptor(
+ "web.search",
+ pluginID: "core.web",
+ summary: "Search the web and return ranked results (title, URL, snippet). Use it for current facts the model can't be sure of — an artist's latest album, today's news, a product spec, an address. Follow up with web.fetch to read a result in full.",
+ input: ["query": "What to search for.", "count": "How many results (default 5, max 10)."],
+ output: ["results": "Ranked results: title — URL, then snippet, per result."],
+ permissions: [],
+ safety: .readOnly,
+ verification: ["the results are relevant to the query"],
+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]
+ ),
+ 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.",
+ input: [
+ "url": "The page URL to read.",
+ "toFile": "\"true\" to write the page text to a temp file and return its path."
+ ],
+ output: [
+ "text": "The page's readable text (a preview when written to a file).",
+ "filePath": "Path to the file holding the full text, when toFile=true."
+ ],
+ permissions: [],
+ safety: .readOnly,
+ verification: ["the fetched text matches the requested page"],
+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]
+ ),
descriptor(
"state.verify",
pluginID: "core.verification",
diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/web-research/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/web-research/SKILL.md
new file mode 100644
index 00000000..f0762bb3
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/web-research/SKILL.md
@@ -0,0 +1,24 @@
+# Web Research
+
+id: web-research
+description: Find current facts on the web and read pages — search, then fetch and read — feeding the result into notes, messages, or other tasks.
+tags: web, search, research, internet, lookup
+keywords: search, look up, google, latest, news, who is, what is, current, find online, website, article, lyrics, tracklist
+tools: web.search, web.fetch, llm.generate
+
+Use this whenever a task needs information you can't be sure of from memory — anything "latest", "current", "today", a specific person/product/place, song lyrics, an album's tracklist. Do NOT guess, and do NOT drive a browser's GUI for this; the web tools are faster and reliable.
+
+## The loop
+1. `web.search` with a focused query → ranked results (title — URL, snippet). Read the snippets.
+2. `web.fetch` the most relevant URL to read the page in full. For a long page, set `toFile=true` and work from the returned file.
+3. Use `llm.generate` to distill what you read into exactly what the task needs (a clean list, a summary, a tracklist), `toFile=true` for long output.
+4. Hand the result to the destination step (create a note from the file, send a message, etc.).
+
+## Examples
+- "Taylor Swift's latest album and its songs": `web.search "Taylor Swift latest album 2026"` → fetch the album page → `llm.generate "From this page, list every track, one per line" toFile=true` → create the note from the file (see the notes skill's long-content pattern).
+- "What's the weather in Tokyo": `web.search "Tokyo weather today"` and read the snippet.
+- "Lyrics for <song>": search → fetch a lyrics page → distill with llm.generate.
+
+## Boundaries
+- Reading the web is safe and runs without consent. The tools only GET pages; they never submit forms, log in, or post.
+- If `web.search` is unavailable (not configured), say so plainly; `web.fetch` still works for a URL the user gives.
diff --git a/apps/Donkey/Sources/DonkeyRuntime/WebTools.swift b/apps/Donkey/Sources/DonkeyRuntime/WebTools.swift
new file mode 100644
index 00000000..3f4d6e7c
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/WebTools.swift
@@ -0,0 +1,90 @@
+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 e32eb67f..14d88c74 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
@@ -246,6 +246,58 @@ struct GenericHarnessTests {
try? FileManager.default.removeItem(atPath: path)
}
+ @Test
+ func webSearchReturnsRankedResultsFromTheSearcher() async {
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
+ services: HarnessBuiltInToolServices(
+ webSearcher: { query in "Latest Album — https://ex.com\nIt's the newest record for \(query)." }
+ )
+ )
+ let result = await registry.execute(
+ HarnessToolCall(name: "web.search", input: ["query": "taylor swift latest album"]),
+ taskID: "t", worldModel: HarnessWorldModel(), grantedPermissions: []
+ )
+ #expect(result.status == .succeeded)
+ #expect(result.metadata["results"]?.contains("https://ex.com") == true)
+ }
+
+ @Test
+ func webFetchWritesLongPagesToAFile() async throws {
+ let page = String(repeating: "paragraph of readable text\n", count: 400)
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
+ services: HarnessBuiltInToolServices(webFetcher: { _ in page })
+ )
+ let result = await registry.execute(
+ HarnessToolCall(name: "web.fetch", input: ["url": "https://ex.com", "toFile": "true"]),
+ taskID: "t", worldModel: HarnessWorldModel(), grantedPermissions: []
+ )
+ #expect(result.status == .succeeded)
+ let path = try #require(result.metadata["filePath"])
+ #expect(try String(contentsOfFile: path, encoding: .utf8) == page)
+ try? FileManager.default.removeItem(atPath: path)
+ }
+
+ @Test
+ func webToolsFailCleanlyWhenNotConfigured() async {
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()
+ let search = await registry.execute(
+ HarnessToolCall(name: "web.search", input: ["query": "x"]),
+ taskID: "t", worldModel: HarnessWorldModel(), grantedPermissions: []
+ )
+ #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()