src / swarm / cache-tools.ts
import { tool } from "@lmstudio/sdk";
import { z } from "zod";
import { scrubPromptInjection } from "../net/scrub";
import { CACHE_CONTRACT_VERSION, publicCacheUrl, type CompanionCacheItem } from "./companion-cache";
import { VisitedPageCache, type CachedVisitedEntry } from "./visited-cache";
const PLUGIN_ID = "mh825/deep-swarm-research-plugin-with-time-limit";
function toCacheItem(entry: CachedVisitedEntry): CompanionCacheItem {
const { source, visitedAt } = entry;
return {
pluginId: PLUGIN_ID,
itemId: source.url,
title: scrubPromptInjection(source.title.slice(0, 200)),
excerpt: scrubPromptInjection(source.text.slice(0, 6000)),
cachedAt: visitedAt,
sourceUrl: publicCacheUrl(source.finalUrl) ?? publicCacheUrl(source.url),
publishedAt: source.published ?? undefined,
};
}
export function createCacheTools(retentionDays: () => number, filePath?: string) {
const cache = () => new VisitedPageCache(retentionDays() || 30, filePath, undefined, true);
return [
tool({
name: "cache_info",
description: "Read the status and freshness of Deep Swarm's visited-page cache.",
parameters: {},
implementation: async () => {
const { available, entries, newestCachedAt } = cache().stats();
return { contractVersion: CACHE_CONTRACT_VERSION, pluginId: PLUGIN_ID,
available, entries, newestCachedAt };
},
}),
tool({
name: "search_cache",
description: "Search previously fetched web pages without fetching the web or changing the cache.",
parameters: {
query: z.string().min(1).max(500),
limit: z.number().int().min(1).max(10).optional(),
since: z.string().datetime({ offset: true }).optional().describe("Earliest cache timestamp, ISO 8601"),
source: z.string().max(253).optional().describe("Exact source hostname"),
},
implementation: async ({ query, limit, since, source }, { signal }) => {
signal.throwIfAborted();
const items = cache().searchEntries(query, limit ?? 5, {
sinceMs: since ? Date.parse(since) : undefined,
source: source?.trim().toLowerCase().replace(/^www\./, ""),
}).map(toCacheItem);
return { contractVersion: CACHE_CONTRACT_VERSION, items };
},
}),
tool({
name: "get_cached_item",
description: "Read a bounded excerpt from a visited-page cache search result.",
parameters: { itemId: z.string().min(1).max(2048) },
implementation: async ({ itemId }, { signal }) => {
signal.throwIfAborted();
const entry = cache().getEntry(itemId);
return { contractVersion: CACHE_CONTRACT_VERSION, item: entry ? toCacheItem(entry) : null };
},
}),
];
}