src / swarm / companion-cache.ts

import { scrubPromptInjection } from "../net/scrub";
import { isPrivateUrl } from "../net/ssrf";
import { buildDomainPolicy, urlAllowed } from "../net/domain-policy";
import type { CrawledSource, ResearchConfig, StatusFn, WarnFn } from "../types";
import { querySiblingPluginCaches, type SiblingCacheHit } from "./pluginBridgeAndPacer";
import { normalizeUrl } from "./visited-cache";
import type { RecordDiagnostic } from "./logger";

export const CACHE_CONTRACT_VERSION = 1;
export const MAX_COMPANION_PLUGINS = 4;
export const COMPANION_TIMEOUT_MS = 3500;

export interface CacheSearchInput {
  query: string;
  limit?: number;
  since?: string;
  source?: string;
}

export interface CompanionCacheItem {
  pluginId: string;
  itemId: string;
  title: string;
  excerpt: string;
  cachedAt: string;
  sourceUrl?: string;
  publishedAt?: string;
}

export interface PluginToolContext {
  status: StatusFn;
  warn: WarnFn;
  signal: AbortSignal;
}

interface PluginTool {
  name: string;
  description?: string;
  readOnly?: boolean;
  checkParameters?(input: Record<string, unknown>): void;
  implementation(input: Record<string, unknown>, context: PluginToolContext): unknown;
}

interface PluginToolSession {
  tools: readonly PluginTool[];
  [Symbol.dispose]?(): void;
  dispose?(): void | Promise<void>;
}

export interface PluginToolsClient {
  plugins?: { pluginTools?(pluginId: string): Promise<PluginToolSession> };
}

export type OpenPluginTools = <T>(pluginId: string, signal: AbortSignal, use: (tools: readonly PluginTool[]) => Promise<T>) => Promise<T>;

export function createPluginToolOpener(client?: PluginToolsClient): OpenPluginTools {
  return async (pluginId, signal, use) => {
    signal.throwIfAborted();
    if (!client?.plugins?.pluginTools) throw new Error("LM Studio's native plugin tools API is unavailable");
    const session = await client.plugins.pluginTools(pluginId);
    let disposed = false;
    const close = async () => {
      if (disposed) return;
      disposed = true;
      try {
        const dispose = session[Symbol.dispose];
        if (dispose) dispose.call(session);
        else await session.dispose?.();
      } catch {
        // Disposal must not replace the remote result or its error.
      }
    };
    const onAbort = () => { void close(); };
    signal.addEventListener("abort", onAbort, { once: true });
    try {
      signal.throwIfAborted();
      return await use(session.tools);
    } finally {
      signal.removeEventListener("abort", onAbort);
      await close();
    }
  };
}

export interface CompanionCacheResult {
  pluginId: string;
  items: CompanionCacheItem[];
  error?: string;
  failureKind?: "denied" | "unavailable" | "contract" | "timeout" | "cancelled" | "call";
}

export type SearchCompanionCache = (pluginId: string, input: CacheSearchInput, context: PluginToolContext) => Promise<CompanionCacheResult>;

export function companionPluginIds(values: readonly string[]): string[] {
  return [...new Set(values)].filter((id) => id.length <= 180 && /^(?:dev\/)?[\w.-]+\/[\w.-]+$/i.test(id)
    && !/\/(?:persistent-memory|deep-swarm-research-plugin-with-time-limit)$/i.test(id)).slice(0, MAX_COMPANION_PLUGINS);
}

function safeText(value: unknown, max: number): string {
  return typeof value === "string" ? scrubPromptInjection(value.slice(0, max)).trim() : "";
}

function isoDate(value: unknown): string | undefined {
  if (typeof value !== "string") return undefined;
  const time = Date.parse(value);
  return Number.isFinite(time) ? new Date(time).toISOString() : undefined;
}

export function publicCacheUrl(value: unknown): string | undefined {
  if (typeof value !== "string" || value.length > 2048 || !/^https?:\/\//i.test(value) || isPrivateUrl(value)) return undefined;
  const url = new URL(value);
  return url.username || url.password ? undefined : url.href;
}

function parseCacheResults(raw: unknown, pluginId: string, limit: number): CompanionCacheItem[] {
  if (typeof raw === "string") {
    if (raw.length > 512_000) throw new Error("Cache response exceeds the size limit");
    raw = JSON.parse(raw);
  }
  if (!raw || typeof raw !== "object") throw new Error("Invalid cache response");
  const response = raw as { contractVersion?: unknown; items?: unknown };
  if (response.contractVersion !== CACHE_CONTRACT_VERSION || !Array.isArray(response.items)) {
    throw new Error("Expected cache contract v1 with an items array");
  }
  const items: CompanionCacheItem[] = [];
  const seen = new Set<string>();
  for (const candidate of response.items.slice(0, limit)) {
    if (!candidate || typeof candidate !== "object") continue;
    const itemId = typeof candidate.itemId === "string" ? candidate.itemId.slice(0, 2048).trim() : "";
    const cachedAt = isoDate(candidate.cachedAt);
    const title = safeText(candidate.title, 200);
    const excerpt = safeText(candidate.excerpt, 6000);
    if (!itemId || !cachedAt || !excerpt || seen.has(itemId)) continue;
    seen.add(itemId);
    items.push({ pluginId, itemId, cachedAt, title: title || "Cached item", excerpt,
      sourceUrl: publicCacheUrl(candidate.sourceUrl), publishedAt: isoDate(candidate.publishedAt) });
  }
  return items;
}

export function createCompanionCacheSearch(open: OpenPluginTools): SearchCompanionCache {
  return async (pluginId, input, context) => {
    const { signal } = context;
    const limit = Math.min(10, Math.max(1, input.limit ?? 5));
    const args = { ...input, query: input.query.trim().slice(0, 500), limit };
    let onAbort: () => void = () => {};
    let failureKind: CompanionCacheResult["failureKind"] = "unavailable";
    try {
      signal.throwIfAborted();
      // The SDK's session opener has no cancellation option. A late session
      // still goes through the opener's finally block and is disposed.
      const aborted = new Promise<never>((_, reject) => {
        onAbort = () => reject(new Error("Timed out or cancelled"));
        signal.addEventListener("abort", onAbort, { once: true });
      });
      const operation = open(pluginId, signal, async (tools) => {
        const target = tools.find((tool) => tool.name === "search_cache");
        if (!target || target.readOnly === false) throw new Error("Read-only search_cache tool is unavailable");
        failureKind = "call";
        target.checkParameters?.(args);
        const raw = await target.implementation(args, context);
        failureKind = "contract";
        return parseCacheResults(raw, pluginId, limit);
      });
      return { pluginId, items: await Promise.race([operation, aborted]) };
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      if (signal.aborted) failureKind = signal.reason?.name === "TimeoutError" ? "timeout" : "cancelled";
      else if (/denied|unauthori[sz]ed|forbidden|permission/i.test(message)) failureKind = "denied";
      return { pluginId, items: [], failureKind, error: message.replace(/[\r\n]+/g, " ").slice(0, 180) };
    } finally {
      signal.removeEventListener("abort", onAbort);
    }
  };
}

type LegacySource = SiblingCacheHit["sourcePlugin"];

function legacySourceForPlugin(pluginId: string): LegacySource | undefined {
  const name = pluginId.slice(pluginId.lastIndexOf("/") + 1).toLowerCase();
  if (name === "rss-rag" || name === "rss-rag-cache") return "rss-rag-cache";
  if (name === "telegram-rag-cache") return name;
  return undefined;
}

export async function collectCompanionSources(
  cfg: Pick<ResearchConfig, "topic" | "allowedDomains" | "blockedDomains" | "companionCachePlugins" | "maxExternalToolCalls">,
  queries: string[],
  legacySources: readonly LegacySource[],
  search: SearchCompanionCache | undefined,
  context: PluginToolContext,
  deadline: number,
  record?: RecordDiagnostic,
): Promise<{ sources: CrawledSource[]; feedCount: number }> {
  const { status, warn, signal } = context;
  const policy = buildDomainPolicy(cfg);
  const sources: CrawledSource[] = [];
  const seen = new Set<string>();
  let feedCount = 0;
  const add = (item: Omit<CompanionCacheItem, "cachedAt" | "itemId"> & { itemId?: string; cachedAt?: string }, score: number) => {
    const sourceUrl = publicCacheUrl(item.sourceUrl);
    if (sourceUrl ? !urlAllowed(sourceUrl, policy).allowed : policy.allowed.size > 0) return;
    const url = sourceUrl ?? `local-plugin://${encodeURIComponent(item.pluginId)}/${encodeURIComponent(item.itemId ?? item.title)}`;
    const key = sourceUrl ? normalizeUrl(url) : url;
    const text = safeText(item.excerpt, 6000);
    if (!text || seen.has(key)) return;
    seen.add(key);
    const published = isoDate(item.publishedAt);
    const ageDays = published ? Math.max(0, (Date.now() - Date.parse(published)) / 86400000) : undefined;
    sources.push({
      url, finalUrl: url, title: safeText(item.title, 200) || "Cached item", description: text.slice(0, 300),
      text, published: published ?? null, wordCount: text.split(/\s+/).length, outlinks: [],
      sourceQuery: cfg.topic, workerRole: "breadth", workerLabel: "Companion cache", domainScore: 70,
      freshnessScore: ageDays === undefined ? 50 : Math.max(0, 100 - ageDays), tier: "reference",
      relevanceScore: Math.max(0.3, Math.min(1, score)), origin: sourceUrl ? "web" : "local",
      discoveredBy: "sibling-cache", companionCache: { pluginId: item.pluginId, itemId: item.itemId, cachedAt: item.cachedAt },
    });
    if (legacySourceForPlugin(item.pluginId)) feedCount++;
  };

  const ids = companionPluginIds(cfg.companionCachePlugins ?? []);
  const cap = cfg.maxExternalToolCalls && cfg.maxExternalToolCalls > 0 ? cfg.maxExternalToolCalls : ids.length;
  const nativeSources = new Set<LegacySource>();
  const nativeBudget = Math.min(COMPANION_TIMEOUT_MS, deadline - Date.now());
  if (ids.length > 0 && !signal.aborted && nativeBudget > 0) {
    if (!search) {
      warn("[Companion cache] LM Studio native tools are unavailable in this research entry point.");
      record?.("companion.native_unavailable", { configured: ids.length });
    }
    else {
      const nativeSignal = AbortSignal.any([signal, AbortSignal.timeout(nativeBudget)]);
      const results = await Promise.all(ids.slice(0, cap).map(async (pluginId) => {
        const started = Date.now();
        const result = await search(pluginId, { query: cfg.topic, limit: 5 }, { ...context, signal: nativeSignal });
        return { result, durationMs: Date.now() - started };
      }));
      for (const { result, durationMs } of results) {
        if (result.error) {
          record?.("companion.native_search", { pluginId: result.pluginId, outcome: result.failureKind ?? "call", durationMs });
          warn(`[Companion cache] ${result.pluginId}: ${result.error}`);
          continue;
        }
        const source = legacySourceForPlugin(result.pluginId);
        if (source) nativeSources.add(source);
        const before = sources.length;
        for (const item of result.items) add(item, 0.7);
        record?.("companion.native_search", { pluginId: result.pluginId, outcome: result.items.length ? "ok" : "empty",
          durationMs, returned: result.items.length, accepted: sources.length - before });
        status(`[Companion cache] ${result.pluginId}: ${sources.length - before} usable item(s).`);
      }
    }
  }

  for (const source of legacySources) {
    if (nativeSources.has(source) || signal.aborted || Date.now() >= deadline) continue;
    const before = sources.length;
    const started = Date.now();
    for (const hit of querySiblingPluginCaches(queries, 5, undefined, { sources: [source], deadline, signal })) {
      const sourceUrl = publicCacheUrl(hit.url);
      add({ pluginId: source, itemId: hit.url, title: hit.title, excerpt: hit.content,
        sourceUrl, publishedAt: hit.timestamp }, hit.score);
    }
    status(`[Companion cache] ${source} legacy files: ${sources.length - before} usable item(s).`);
    record?.("companion.legacy_search", { pluginId: source, durationMs: Date.now() - started,
      accepted: sources.length - before, deadlineReached: Date.now() >= deadline });
  }
  return { sources, feedCount };
}