@blackdrome/open-deepresearch 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/LICENSE +17 -0
- package/README.md +133 -0
- package/dist/index.cjs +928 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +193 -0
- package/dist/index.d.ts +193 -0
- package/dist/index.js +889 -0
- package/dist/index.js.map +1 -0
- package/package.json +59 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/constraints.ts","../src/validators/truth-contract.ts","../src/utils/text.ts","../src/core/engine.ts","../src/adapters/llm/openrouter.ts","../src/adapters/llm/nim.ts","../src/adapters/llm/function-adapter.ts","../src/adapters/search/http-json.ts"],"sourcesContent":["export * from \"./types\";\nexport * from \"./constraints\";\nexport * from \"./validators/truth-contract\";\nexport { OpenDeepResearchEngine } from \"./core/engine\";\nexport { OpenRouterAdapter, type OpenRouterAdapterConfig } from \"./adapters/llm/openrouter\";\nexport { NimAdapter, type NimAdapterConfig } from \"./adapters/llm/nim\";\nexport { FunctionLlmAdapter, type FunctionAdapterConfig } from \"./adapters/llm/function-adapter\";\nexport { HttpJsonSearchAdapter, type HttpJsonSearchAdapterConfig } from \"./adapters/search/http-json\";\n\nimport type { DeepResearchEngineConfig, LlmAdapter, LlmProviderId, SearchAdapter } from \"./types\";\nimport { OpenDeepResearchEngine } from \"./core/engine\";\nimport { OpenRouterAdapter, type OpenRouterAdapterConfig } from \"./adapters/llm/openrouter\";\nimport { NimAdapter, type NimAdapterConfig } from \"./adapters/llm/nim\";\nimport { FunctionLlmAdapter } from \"./adapters/llm/function-adapter\";\n\nexport type CreateEngineOptions = {\n searchAdapter: SearchAdapter;\n defaultProvider?: LlmProviderId;\n openRouter?: OpenRouterAdapterConfig;\n nim?: NimAdapterConfig;\n fallbackComplete?: (prompt: string) => Promise<string>;\n};\n\nexport const createOpenDeepResearchEngine = (options: CreateEngineOptions) => {\n const llmAdapters: Partial<Record<LlmProviderId, LlmAdapter>> = {};\n\n if (options.openRouter) {\n llmAdapters.openrouter = new OpenRouterAdapter(options.openRouter);\n }\n\n if (options.nim) {\n llmAdapters.nim = new NimAdapter(options.nim);\n }\n\n if (options.fallbackComplete) {\n llmAdapters.fallback = new FunctionLlmAdapter({\n provider: \"fallback\",\n complete: options.fallbackComplete,\n });\n }\n\n const defaultProvider = options.defaultProvider || \"openrouter\";\n const config: DeepResearchEngineConfig = {\n searchAdapter: options.searchAdapter,\n llmAdapters,\n defaultProvider,\n };\n\n return new OpenDeepResearchEngine(config);\n};\n","import type { SearchConstraints } from \"./types\";\n\nconst FORUM_DOMAIN_MAP: Array<{ pattern: RegExp; domain: string; hint: string }> = [\n { pattern: /\\breddit\\b|\\br\\/[a-z0-9_]+/i, domain: \"reddit.com\", hint: \"reddit\" },\n { pattern: /\\bstack\\s*overflow\\b/i, domain: \"stackoverflow.com\", hint: \"stackoverflow\" },\n { pattern: /\\bstack\\s*exchange\\b|\\bstackexchange\\b/i, domain: \"stackexchange.com\", hint: \"stackexchange\" },\n { pattern: /\\bhacker\\s*news\\b|\\bhn\\b/i, domain: \"news.ycombinator.com\", hint: \"hackernews\" },\n { pattern: /\\bquora\\b/i, domain: \"quora.com\", hint: \"quora\" },\n { pattern: /\\bgithub\\s+issues\\b/i, domain: \"github.com\", hint: \"github\" },\n];\n\nconst STRICT_FORUM_PATTERN =\n /\\b(?:only|just|strictly|specifically)\\b.*\\b(reddit|stack\\s*overflow|stack\\s*exchange|stackexchange|hacker\\s*news|quora|github)\\b/i;\n\nconst FORUM_PREPOSITION_PATTERN =\n /\\b(?:from|on|in)\\s+(reddit|stack\\s*overflow|stack\\s*exchange|stackexchange|hacker\\s*news|quora|github)\\b/i;\n\nexport const normalizeDomain = (value: string) =>\n value.trim().toLowerCase().replace(/^https?:\\/\\//, \"\").replace(/^www\\./, \"\");\n\nconst unique = (items: string[]) => Array.from(new Set(items.filter(Boolean).map(normalizeDomain)));\n\nexport const extractSiteTokens = (query: string) => {\n const matches = Array.from(query.matchAll(/site:([a-z0-9.-]+)/gi));\n return unique(matches.map((entry) => entry[1]));\n};\n\nexport const extractSearchConstraints = (query: string): SearchConstraints => {\n const q = query || \"\";\n const explicitSites = extractSiteTokens(q);\n const preferredDomains: string[] = [];\n const forumHints: string[] = [];\n\n for (const forum of FORUM_DOMAIN_MAP) {\n if (!forum.pattern.test(q)) continue;\n preferredDomains.push(forum.domain);\n forumHints.push(forum.hint);\n }\n\n const enforceByLanguage = STRICT_FORUM_PATTERN.test(q) || FORUM_PREPOSITION_PATTERN.test(q);\n const enforceRequiredDomains = explicitSites.length > 0 || (preferredDomains.length > 0 && enforceByLanguage);\n const requiredDomains = enforceRequiredDomains\n ? explicitSites.length > 0\n ? explicitSites\n : preferredDomains\n : explicitSites;\n\n return {\n requiredDomains: unique(requiredDomains),\n preferredDomains: unique(preferredDomains),\n enforceRequiredDomains,\n forumHints: Array.from(new Set(forumHints)),\n };\n};\n\nexport const domainMatches = (urlOrDomain: string, targetDomains: string[]) => {\n if (!targetDomains.length) return true;\n\n let host = normalizeDomain(urlOrDomain);\n try {\n host = normalizeDomain(new URL(urlOrDomain).hostname);\n } catch {\n host = normalizeDomain(urlOrDomain);\n }\n\n return targetDomains.some((targetRaw) => {\n const target = normalizeDomain(targetRaw);\n return host === target || host.endsWith(`.${target}`);\n });\n};\n\nexport const mergeConstraints = (\n base: SearchConstraints,\n incoming?: Partial<SearchConstraints>\n): SearchConstraints => {\n const requiredDomains = unique([...(base.requiredDomains || []), ...(incoming?.requiredDomains || [])]);\n const preferredDomains = unique([...(base.preferredDomains || []), ...(incoming?.preferredDomains || [])]);\n const forumHints = Array.from(new Set([...(base.forumHints || []), ...(incoming?.forumHints || [])]));\n const enforceRequiredDomains = Boolean(\n incoming?.enforceRequiredDomains ?? (base.enforceRequiredDomains || requiredDomains.length > 0)\n );\n\n return {\n requiredDomains,\n preferredDomains,\n forumHints,\n enforceRequiredDomains,\n };\n};\n","export type TruthContractStrictness = \"standard\" | \"strict\";\n\nexport type TruthContractCheck = {\n passed: boolean;\n violations: string[];\n};\n\nexport const buildTruthContractInstruction = (strictness: TruthContractStrictness) => {\n const strictLine =\n strictness === \"strict\"\n ? \"Do not present uncertain claims as facts. If uncertain, explicitly state uncertainty.\"\n : \"Prefer high-confidence claims and note uncertainty briefly when needed.\";\n\n return [\n \"TRUTH CONTRACT:\",\n \"- Lead with the direct answer in 1-2 sentences.\",\n \"- Do not invent sources or facts.\",\n \"- If web or dossier sources are provided, cite claims as [1], [2], etc.\",\n \"- Include a short 'What is uncertain' note when confidence is limited.\",\n strictLine,\n ].join(\"\\n\");\n};\n\nexport const evaluateTruthContract = (\n response: string,\n options?: { requiresCitations?: boolean; strictness?: TruthContractStrictness }\n): TruthContractCheck => {\n const text = (response || \"\").trim();\n const violations: string[] = [];\n\n if (!text) {\n return {\n passed: false,\n violations: [\"Empty response\"],\n };\n }\n\n const hasCitation = /\\[\\d+\\]/.test(text);\n if (options?.requiresCitations && !hasCitation) {\n violations.push(\"Missing source citations in bracket format like [1]\");\n }\n\n const hasUncertaintySection = /what is uncertain/i.test(text) || /uncertain|not enough evidence|insufficient data/i.test(text);\n if (options?.strictness === \"strict\" && !hasUncertaintySection) {\n violations.push(\"No explicit uncertainty note found in strict mode\");\n }\n\n const hasOverconfidentPhrases = /guaranteed|always true|definitely 100%|undeniably/i.test(text);\n if (hasOverconfidentPhrases) {\n violations.push(\"Contains overconfident phrasing\");\n }\n\n return {\n passed: violations.length === 0,\n violations,\n };\n};\n","const STOPWORDS = new Set([\n \"the\",\n \"a\",\n \"an\",\n \"and\",\n \"or\",\n \"to\",\n \"for\",\n \"of\",\n \"in\",\n \"on\",\n \"with\",\n \"is\",\n \"are\",\n \"was\",\n \"were\",\n \"be\",\n \"as\",\n \"at\",\n \"from\",\n \"by\",\n \"that\",\n \"this\",\n \"it\",\n \"about\",\n \"into\",\n \"what\",\n \"which\",\n \"who\",\n \"when\",\n \"where\",\n \"how\",\n]);\n\nexport const NEGATION_TERMS = [\"not\", \"never\", \"no\", \"without\", \"cannot\", \"can't\", \"didn't\"];\n\nexport const normalizeUrl = (url: string) => {\n try {\n const parsed = new URL(url);\n parsed.hash = \"\";\n [\"utm_source\", \"utm_medium\", \"utm_campaign\", \"utm_term\", \"utm_content\"].forEach((key) => {\n parsed.searchParams.delete(key);\n });\n return parsed.toString();\n } catch {\n return url.trim();\n }\n};\n\nexport const domainOf = (url: string) => {\n try {\n return new URL(url).hostname.replace(/^www\\./, \"\").toLowerCase();\n } catch {\n return url.trim().toLowerCase();\n }\n};\n\nexport const toTokens = (text: string) =>\n text\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \" \")\n .split(/\\s+/)\n .map((token) => token.trim())\n .filter((token) => token.length > 2 && !STOPWORDS.has(token));\n\nexport const lexicalScore = (query: string, text: string) => {\n const queryTokens = toTokens(query);\n if (!queryTokens.length) return 0;\n\n const textTokens = new Set(toTokens(text));\n let hits = 0;\n for (const token of queryTokens) {\n if (textTokens.has(token)) hits += 1;\n }\n return hits / queryTokens.length;\n};\n\nexport const jaccardSimilarity = (a: string, b: string) => {\n const aTokens = new Set(toTokens(a));\n const bTokens = new Set(toTokens(b));\n if (!aTokens.size || !bTokens.size) return 0;\n\n let intersection = 0;\n for (const token of aTokens) {\n if (bTokens.has(token)) intersection += 1;\n }\n\n const union = aTokens.size + bTokens.size - intersection;\n return union === 0 ? 0 : intersection / union;\n};\n\nexport const sentenceCandidates = (snippet: string) =>\n snippet\n .split(/(?<=[.!?])\\s+/)\n .map((sentence) => sentence.trim())\n .filter((sentence) => sentence.length >= 35)\n .slice(0, 2);\n\nexport const hasNegation = (text: string) => {\n const lower = text.toLowerCase();\n return NEGATION_TERMS.some((term) => lower.includes(term));\n};\n\nexport const extractNumericTokens = (text: string) => Array.from(text.matchAll(/\\b\\d+(?:\\.\\d+)?%?\\b/g)).map((m) => m[0]);\n\nexport const authorityScore = (domain: string) => {\n if (domain.endsWith(\".gov\") || domain.endsWith(\".edu\")) return 1;\n if (domain.includes(\"wikipedia.org\")) return 0.9;\n if (domain.includes(\"stackoverflow.com\") || domain.includes(\"stackexchange.com\")) return 0.85;\n if (domain.includes(\"github.com\")) return 0.8;\n if (domain.includes(\"reddit.com\")) return 0.72;\n return 0.56;\n};\n\nexport const recencyScore = (text: string, url: string) => {\n const year = new Date().getFullYear();\n const bag = `${text} ${url}`;\n if (bag.includes(String(year))) return 1;\n if (bag.includes(String(year - 1))) return 0.82;\n if (bag.includes(String(year - 2))) return 0.65;\n return 0.48;\n};\n","import { domainMatches, extractSearchConstraints, mergeConstraints } from \"../constraints\";\nimport type {\n ClaimCluster,\n DeepResearchDepth,\n DeepResearchEngineConfig,\n DeepResearchProgress,\n DeepResearchRun,\n DeepResearchRunOptions,\n PlannedQuery,\n RankedSource,\n SearchConstraints,\n SearchResult,\n} from \"../types\";\nimport {\n authorityScore,\n domainOf,\n extractNumericTokens,\n hasNegation,\n jaccardSimilarity,\n lexicalScore,\n normalizeUrl,\n recencyScore,\n sentenceCandidates,\n} from \"../utils/text\";\nimport { buildTruthContractInstruction, evaluateTruthContract } from \"../validators/truth-contract\";\n\nconst DEPTH_CONFIG: Record<\n DeepResearchDepth,\n {\n initialQueries: number;\n refinementQueries: number;\n sourceLimit: number;\n maxPerDomain: number;\n minDomainDiversity: number;\n }\n> = {\n standard: {\n initialQueries: 5,\n refinementQueries: 2,\n sourceLimit: 12,\n maxPerDomain: 3,\n minDomainDiversity: 3,\n },\n deep: {\n initialQueries: 8,\n refinementQueries: 4,\n sourceLimit: 20,\n maxPerDomain: 4,\n minDomainDiversity: 4,\n },\n extreme: {\n initialQueries: 12,\n refinementQueries: 6,\n sourceLimit: 30,\n maxPerDomain: 5,\n minDomainDiversity: 5,\n },\n};\n\nconst confidenceFromSupport = (citations: number, domains: number): ClaimCluster[\"confidence\"] => {\n if (citations >= 3 && domains >= 2) return \"high\";\n if (citations >= 2) return \"medium\";\n return \"low\";\n};\n\nexport class OpenDeepResearchEngine {\n private readonly resultCache = new Map<string, SearchResult[]>();\n\n constructor(private readonly config: DeepResearchEngineConfig) {}\n\n private emit(\n onProgress: ((progress: DeepResearchProgress) => void) | undefined,\n stage: DeepResearchProgress[\"stage\"],\n message: string,\n completed: number,\n total: number\n ) {\n onProgress?.({ stage, message, completed, total });\n }\n\n private buildPlan(query: string, depth: DeepResearchDepth, constraints: SearchConstraints): PlannedQuery[] {\n const cfg = DEPTH_CONFIG[depth];\n\n const seed: PlannedQuery[] = [\n { query, intent: \"Core answer\" },\n { query: `${query} latest updates facts`, intent: \"Fresh context\" },\n { query: `${query} benchmark comparison`, intent: \"Comparative evidence\" },\n { query: `${query} data statistics report`, intent: \"Quantitative evidence\" },\n { query: `${query} criticism limitations`, intent: \"Counter evidence\" },\n { query: `${query} implementation guide`, intent: \"Practical implementation\" },\n { query: `${query} official documentation`, intent: \"Primary source\" },\n { query: `${query} common mistakes pitfalls`, intent: \"Failure patterns\" },\n { query: `${query} timeline history`, intent: \"Historical context\" },\n { query: `${query} expert analysis`, intent: \"Expert opinion\" },\n ];\n\n for (const domain of constraints.requiredDomains.slice(0, 4)) {\n seed.unshift({\n query: `${query} site:${domain}`,\n intent: `Required domain evidence (${domain})`,\n constrainedToDomain: domain,\n });\n }\n\n for (const domain of constraints.preferredDomains.slice(0, 3)) {\n seed.unshift({\n query: `${query} discussion site:${domain}`,\n intent: `Preferred domain signal (${domain})`,\n constrainedToDomain: domain,\n });\n }\n\n const unique = new Map<string, PlannedQuery>();\n for (const row of seed) {\n const key = row.query.toLowerCase().trim();\n if (!unique.has(key)) unique.set(key, row);\n }\n\n return Array.from(unique.values()).slice(0, cfg.initialQueries);\n }\n\n private buildRefinementQueries(\n query: string,\n rankedSources: RankedSource[],\n constraints: SearchConstraints,\n depth: DeepResearchDepth\n ): PlannedQuery[] {\n const cfg = DEPTH_CONFIG[depth];\n const diversity = new Set(rankedSources.map((source) => source.domain)).size;\n const lowDiversity = diversity < cfg.minDomainDiversity;\n\n const candidates: PlannedQuery[] = [\n { query: `${query} contradictory findings`, intent: \"Conflict checks\" },\n { query: `${query} independent validation`, intent: \"Independent corroboration\" },\n { query: `${query} known caveats`, intent: \"Known caveats\" },\n { query: `${query} recent updates this year`, intent: \"Recency refresh\" },\n { query: `${query} real world case study`, intent: \"Case studies\" },\n ];\n\n if (lowDiversity) {\n candidates.push({ query: `${query} alternative sources analysis`, intent: \"Diversity expansion\" });\n }\n\n for (const domain of constraints.requiredDomains.slice(0, 3)) {\n candidates.push({\n query: `${query} site:${domain}`,\n intent: `Required domain refinement (${domain})`,\n constrainedToDomain: domain,\n });\n }\n\n const unique = new Map<string, PlannedQuery>();\n for (const row of candidates) {\n const key = row.query.toLowerCase().trim();\n if (!unique.has(key)) unique.set(key, row);\n }\n\n return Array.from(unique.values()).slice(0, cfg.refinementQueries);\n }\n\n private async retrieveWithCache(query: string, constraints: SearchConstraints): Promise<SearchResult[]> {\n const cacheKey = [\n query.toLowerCase().trim(),\n constraints.requiredDomains.join(\",\"),\n constraints.preferredDomains.join(\",\"),\n String(constraints.enforceRequiredDomains),\n ].join(\"|\");\n\n const cached = this.resultCache.get(cacheKey);\n if (cached) return cached;\n\n const results = await this.config.searchAdapter.search(query, {\n sites: constraints.requiredDomains,\n preferredSites: constraints.preferredDomains,\n enforceSites: constraints.enforceRequiredDomains,\n forumHints: constraints.forumHints,\n });\n\n const filtered = results.filter((result) => result.url && result.url !== \"#\" && result.title !== \"Search Error\");\n this.resultCache.set(cacheKey, filtered);\n return filtered;\n }\n\n private rank(\n question: string,\n rows: Array<{ plannedQuery: string; constrainedToDomain?: string; result: SearchResult }>,\n depth: DeepResearchDepth,\n constraints: SearchConstraints\n ): RankedSource[] {\n const cfg = DEPTH_CONFIG[depth];\n const deduped = new Set<string>();\n const scored: RankedSource[] = [];\n\n for (const row of rows) {\n const url = normalizeUrl(row.result.url);\n if (!url || deduped.has(url)) continue;\n deduped.add(url);\n\n const domain = domainOf(url);\n if (constraints.enforceRequiredDomains && constraints.requiredDomains.length > 0) {\n if (!domainMatches(domain, constraints.requiredDomains)) continue;\n }\n\n const preferredBoost =\n constraints.preferredDomains.length > 0 && domainMatches(domain, constraints.preferredDomains) ? 1 : 0;\n const constrainedBoost = row.constrainedToDomain && domainMatches(domain, [row.constrainedToDomain]) ? 1 : 0;\n\n const score =\n lexicalScore(question, `${row.result.title} ${row.result.snippet}`) * 0.45 +\n lexicalScore(row.plannedQuery, `${row.result.title} ${row.result.snippet}`) * 0.15 +\n authorityScore(domain) * 0.15 +\n recencyScore(`${row.result.title} ${row.result.snippet}`, url) * 0.1 +\n preferredBoost * 0.1 +\n constrainedBoost * 0.05;\n\n scored.push({\n id: 0,\n title: row.result.title,\n snippet: row.result.snippet,\n url,\n domain,\n score,\n retrievedFrom: row.plannedQuery,\n });\n }\n\n scored.sort((a, b) => b.score - a.score);\n\n const diversified: RankedSource[] = [];\n const domainCounts = new Map<string, number>();\n\n for (const source of scored) {\n const seenFromDomain = domainCounts.get(source.domain) || 0;\n if (seenFromDomain >= cfg.maxPerDomain) continue;\n\n diversified.push(source);\n domainCounts.set(source.domain, seenFromDomain + 1);\n if (diversified.length >= cfg.sourceLimit) break;\n }\n\n return diversified.map((entry, index) => ({ ...entry, id: index + 1 }));\n }\n\n private verify(rankedSources: RankedSource[]): {\n claims: ClaimCluster[];\n contradictions: string[];\n unresolvedQuestions: string[];\n } {\n const clusters: Array<{\n claim: string;\n citationIds: Set<number>;\n domains: Set<string>;\n }> = [];\n\n for (const source of rankedSources) {\n const candidates = sentenceCandidates(source.snippet || source.title);\n if (!candidates.length && source.title) candidates.push(source.title);\n\n for (const sentence of candidates) {\n let attached = false;\n for (const cluster of clusters) {\n if (jaccardSimilarity(cluster.claim, sentence) >= 0.66) {\n cluster.citationIds.add(source.id);\n cluster.domains.add(source.domain);\n attached = true;\n break;\n }\n }\n\n if (!attached) {\n clusters.push({\n claim: sentence,\n citationIds: new Set([source.id]),\n domains: new Set([source.domain]),\n });\n }\n }\n }\n\n const claims = clusters\n .map<ClaimCluster>((cluster) => {\n const citationIds = Array.from(cluster.citationIds).sort((a, b) => a - b);\n const domains = Array.from(cluster.domains);\n return {\n claim: cluster.claim,\n citationIds,\n domains,\n confidence: confidenceFromSupport(citationIds.length, domains.length),\n };\n })\n .sort((a, b) => {\n const scoreA = a.citationIds.length * 10 + (a.confidence === \"high\" ? 3 : a.confidence === \"medium\" ? 2 : 1);\n const scoreB = b.citationIds.length * 10 + (b.confidence === \"high\" ? 3 : b.confidence === \"medium\" ? 2 : 1);\n return scoreB - scoreA;\n })\n .slice(0, 20);\n\n const contradictions: string[] = [];\n for (let i = 0; i < claims.length; i += 1) {\n for (let j = i + 1; j < claims.length; j += 1) {\n const left = claims[i];\n const right = claims[j];\n if (jaccardSimilarity(left.claim, right.claim) < 0.78) continue;\n\n const negationConflict = hasNegation(left.claim) !== hasNegation(right.claim);\n const leftNumbers = extractNumericTokens(left.claim);\n const rightNumbers = extractNumericTokens(right.claim);\n const numericConflict =\n leftNumbers.length > 0 && rightNumbers.length > 0 && leftNumbers.join(\"|\") !== rightNumbers.join(\"|\");\n\n if (negationConflict || numericConflict) {\n contradictions.push(\n `Potential conflict between [${left.citationIds[0]}] and [${right.citationIds[0]}] on similar claim wording.`\n );\n }\n }\n }\n\n const unresolvedQuestions = claims\n .filter((claim) => claim.confidence === \"low\")\n .slice(0, 4)\n .map((claim) => `Need stronger corroboration for: ${claim.claim}`);\n\n return {\n claims,\n contradictions: Array.from(new Set(contradictions)).slice(0, 6),\n unresolvedQuestions,\n };\n }\n\n private buildPromptContext(params: {\n query: string;\n depth: DeepResearchDepth;\n plan: PlannedQuery[];\n retrievalRounds: number;\n constraints: SearchConstraints;\n claims: ClaimCluster[];\n contradictions: string[];\n unresolvedQuestions: string[];\n rankedSources: RankedSource[];\n contextBlocks?: string[];\n }) {\n const constraintsLine = params.constraints.requiredDomains.length\n ? `Required domains: ${params.constraints.requiredDomains.join(\", \")} (strict=${String(\n params.constraints.enforceRequiredDomains\n )})`\n : params.constraints.preferredDomains.length\n ? `Preferred domains: ${params.constraints.preferredDomains.join(\", \")}`\n : \"No strict domain constraints requested.\";\n\n const sourcePayload = params.rankedSources.map((source) => ({\n id: source.id,\n title: source.title,\n snippet: source.snippet,\n url: source.url,\n domain: source.domain,\n score: Number(source.score.toFixed(4)),\n retrievedFrom: source.retrievedFrom,\n }));\n\n const claimPayload = params.claims.map((claim) => ({\n claim: claim.claim,\n confidence: claim.confidence,\n citations: claim.citationIds,\n domains: claim.domains,\n }));\n\n const contextSection = (params.contextBlocks || []).filter(Boolean);\n\n return [\n \"UPAI OPEN DEEPRESEARCH DOSSIER\",\n `Question: ${params.query}`,\n `Depth: ${params.depth}`,\n `Retrieval rounds: ${params.retrievalRounds}`,\n constraintsLine,\n \"\",\n ...(contextSection.length ? [\"Additional context:\", ...contextSection, \"\"] : []),\n \"Research plan:\",\n ...params.plan.map((entry, index) => `${index + 1}. ${entry.intent}: ${entry.query}`),\n \"\",\n \"Claim graph:\",\n \"```json\",\n JSON.stringify(claimPayload, null, 2),\n \"```\",\n \"\",\n \"Evidence table:\",\n \"```json\",\n JSON.stringify(sourcePayload, null, 2),\n \"```\",\n \"\",\n \"Contradictions:\",\n params.contradictions.length ? params.contradictions.join(\"\\n\") : \"None detected.\",\n \"\",\n \"Unresolved questions:\",\n params.unresolvedQuestions.length ? params.unresolvedQuestions.join(\"\\n\") : \"None\",\n \"\",\n \"Answer requirements:\",\n \"1) Start with a direct answer in 1-2 sentences.\",\n \"2) Use only evidence supported by citations from this dossier.\",\n \"3) Cite evidence as [1], [2], ... with bracket IDs.\",\n \"4) Add a short 'What is uncertain' section.\",\n \"5) If contradictions exist, explicitly mention them.\",\n \"6) Respect required/preferred domain constraints in framing.\",\n \"\",\n buildTruthContractInstruction(\"strict\"),\n ].join(\"\\n\");\n }\n\n private async synthesize(promptContext: string, providerHint?: DeepResearchRunOptions[\"providerHint\"]) {\n const order: Array<\"openrouter\" | \"nim\" | \"fallback\"> = [];\n if (providerHint) order.push(providerHint);\n if (!order.includes(this.config.defaultProvider)) order.push(this.config.defaultProvider);\n for (const key of [\"openrouter\", \"nim\", \"fallback\"] as const) {\n if (!order.includes(key)) order.push(key);\n }\n\n const errors: string[] = [];\n for (const provider of order) {\n const adapter = this.config.llmAdapters[provider];\n if (!adapter) continue;\n\n try {\n const answer = await adapter.complete(`${promptContext}\\n\\nNow produce the final answer.`);\n if (answer.trim()) {\n return { provider, answer };\n }\n } catch (error) {\n errors.push(`${provider}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n throw new Error(`All synthesis providers failed. ${errors.join(\" | \")}`);\n }\n\n async run(query: string, options?: DeepResearchRunOptions): Promise<DeepResearchRun> {\n const depth = options?.depth || \"deep\";\n const onProgress = options?.onProgress;\n const cfg = DEPTH_CONFIG[depth];\n\n const inferred = extractSearchConstraints(query);\n const constraints = mergeConstraints(inferred, options?.constraints);\n\n this.emit(onProgress, \"planning\", \"Planning multi-angle research queries...\", 1, 6);\n const plan = this.buildPlan(query, depth, constraints);\n\n const gathered: Array<{ plannedQuery: string; constrainedToDomain?: string; result: SearchResult }> = [];\n\n this.emit(onProgress, \"retrieving\", \"Running retrieval round 1...\", 2, 6);\n for (let index = 0; index < plan.length; index += 1) {\n const step = plan[index];\n this.emit(onProgress, \"retrieving\", `Query ${index + 1}/${plan.length}: ${step.intent}`, 2, 6);\n\n const results = await this.retrieveWithCache(step.query, constraints);\n for (const result of results) {\n gathered.push({ plannedQuery: step.query, constrainedToDomain: step.constrainedToDomain, result });\n }\n }\n\n let retrievalRounds = 1;\n let rankedSources = this.rank(query, gathered, depth, constraints);\n const diversity = new Set(rankedSources.map((source) => source.domain)).size;\n const needsRefinement =\n depth !== \"standard\" &&\n (rankedSources.length < Math.floor(cfg.sourceLimit * 0.7) || diversity < cfg.minDomainDiversity);\n\n if (needsRefinement) {\n retrievalRounds += 1;\n const refinementPlan = this.buildRefinementQueries(query, rankedSources, constraints, depth);\n this.emit(onProgress, \"retrieving\", \"Running adaptive refinement queries...\", 2, 6);\n\n for (let index = 0; index < refinementPlan.length; index += 1) {\n const step = refinementPlan[index];\n this.emit(onProgress, \"retrieving\", `Refinement ${index + 1}/${refinementPlan.length}: ${step.intent}`, 2, 6);\n\n const results = await this.retrieveWithCache(step.query, constraints);\n for (const result of results) {\n gathered.push({ plannedQuery: step.query, constrainedToDomain: step.constrainedToDomain, result });\n }\n }\n\n rankedSources = this.rank(query, gathered, depth, constraints);\n }\n\n this.emit(onProgress, \"ranking\", \"Ranking and diversifying evidence...\", 3, 6);\n this.emit(onProgress, \"verifying\", \"Building claim graph and contradiction checks...\", 4, 6);\n const { claims, contradictions, unresolvedQuestions } = this.verify(rankedSources);\n\n this.emit(onProgress, \"synthesizing\", \"Synthesizing final answer with citations...\", 5, 6);\n const promptContext = this.buildPromptContext({\n query,\n depth,\n plan,\n retrievalRounds,\n constraints,\n claims,\n contradictions,\n unresolvedQuestions,\n rankedSources,\n contextBlocks: options?.contextBlocks,\n });\n\n const synthesis = await this.synthesize(promptContext, options?.providerHint);\n let finalAnswer = synthesis.answer;\n\n this.emit(onProgress, \"critiquing\", \"Running citation/uncertainty critique pass...\", 6, 6);\n const critique = evaluateTruthContract(finalAnswer, {\n requiresCitations: rankedSources.length > 0,\n strictness: \"strict\",\n });\n\n if (!critique.passed) {\n const repairPrompt = [\n promptContext,\n \"\",\n \"Your previous answer violated the response contract.\",\n `Violations: ${critique.violations.join(\"; \")}`,\n \"Rewrite the answer to satisfy all requirements.\",\n \"\",\n \"Previous answer:\",\n finalAnswer,\n ].join(\"\\n\");\n\n const adapter = this.config.llmAdapters[synthesis.provider];\n if (adapter) {\n try {\n const repaired = await adapter.complete(repairPrompt);\n if (repaired.trim()) finalAnswer = repaired;\n } catch {\n // Keep original answer if repair fails\n }\n }\n }\n\n const sourcesForMessage: SearchResult[] = rankedSources.map((source) => ({\n title: source.title,\n snippet: source.snippet,\n url: source.url,\n }));\n\n return {\n query,\n depth,\n plan,\n retrievalRounds,\n rankedSources,\n claims,\n contradictions,\n unresolvedQuestions,\n promptContext,\n finalAnswer,\n synthesis: {\n provider: synthesis.provider,\n critiqueViolations: critique.violations,\n },\n constraints,\n sourcesForMessage,\n };\n }\n}\n","import type { LlmAdapter } from \"../../types\";\n\nexport type OpenRouterAdapterConfig = {\n apiKey: string;\n model: string;\n endpoint?: string;\n siteUrl?: string;\n siteName?: string;\n timeoutMs?: number;\n};\n\ntype OpenRouterResponse = {\n choices?: Array<{\n message?: {\n content?: string;\n };\n }>;\n error?: {\n message?: string;\n };\n};\n\nexport class OpenRouterAdapter implements LlmAdapter {\n provider = \"openrouter\" as const;\n private readonly endpoint: string;\n private readonly timeoutMs: number;\n private readonly siteUrl: string;\n private readonly siteName: string;\n\n constructor(private readonly config: OpenRouterAdapterConfig) {\n this.endpoint = config.endpoint || \"https://openrouter.ai/api/v1/chat/completions\";\n this.timeoutMs = config.timeoutMs || 60000;\n this.siteUrl = config.siteUrl || \"https://github.com/blackdrome/upai-open-deepresearch\";\n this.siteName = config.siteName || \"UPAI Open DeepResearch\";\n }\n\n async complete(prompt: string): Promise<string> {\n if (!this.config.apiKey) {\n throw new Error(\"OpenRouter API key is required.\");\n }\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n const response = await fetch(this.endpoint, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.config.apiKey}`,\n \"Content-Type\": \"application/json\",\n \"HTTP-Referer\": this.siteUrl,\n \"X-Title\": this.siteName,\n },\n body: JSON.stringify({\n model: this.config.model,\n messages: [\n {\n role: \"system\",\n content: \"You are a grounded research synthesis model. Keep claims source-bound and concise.\",\n },\n {\n role: \"user\",\n content: prompt,\n },\n ],\n stream: false,\n temperature: 0.2,\n }),\n signal: controller.signal,\n });\n\n const raw = await response.text();\n let payload: OpenRouterResponse | null = null;\n try {\n payload = JSON.parse(raw) as OpenRouterResponse;\n } catch {\n payload = null;\n }\n\n if (!response.ok) {\n throw new Error(payload?.error?.message || raw || `OpenRouter request failed (${response.status})`);\n }\n\n const text = payload?.choices?.[0]?.message?.content?.trim();\n if (!text) {\n throw new Error(\"OpenRouter returned an empty completion.\");\n }\n\n return text;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n","import type { LlmAdapter } from \"../../types\";\n\nexport type NimAdapterConfig = {\n apiKey: string;\n model: string;\n endpoint?: string;\n timeoutMs?: number;\n maxTokens?: number;\n temperature?: number;\n};\n\ntype NimResponse = {\n choices?: Array<{\n message?: {\n content?: string | Array<{ type?: string; text?: string }>;\n };\n }>;\n error?: {\n message?: string;\n };\n message?: string;\n detail?: string;\n};\n\nconst normalizeNimError = (status: number, raw: string, parsed?: NimResponse | null) => {\n const text = parsed?.error?.message || parsed?.message || parsed?.detail || raw || `NIM request failed (${status})`;\n const lowered = text.toLowerCase();\n\n if (lowered.includes(\"not found for account\") || /function\\s+'[^']+'\\s*:\\s*not found/i.test(text)) {\n return \"Selected NVIDIA NIM model is unavailable for this account.\";\n }\n\n if (status === 401 || lowered.includes(\"authentication\") || lowered.includes(\"invalid api key\")) {\n return \"NVIDIA NIM authentication failed. Verify your API key.\";\n }\n\n if (status === 429 || lowered.includes(\"rate limit\")) {\n return \"NVIDIA NIM rate limit reached. Retry later or switch model.\";\n }\n\n if (status === 408 || lowered.includes(\"timed out\") || lowered.includes(\"timeout\")) {\n return \"NVIDIA NIM timed out. Try a faster model or reduce response size.\";\n }\n\n return text;\n};\n\nexport class NimAdapter implements LlmAdapter {\n provider = \"nim\" as const;\n private readonly endpoint: string;\n private readonly timeoutMs: number;\n private readonly maxTokens: number;\n private readonly temperature: number;\n\n constructor(private readonly config: NimAdapterConfig) {\n this.endpoint = config.endpoint || \"https://integrate.api.nvidia.com/v1/chat/completions\";\n this.timeoutMs = config.timeoutMs || 70000;\n this.maxTokens = config.maxTokens || 1100;\n this.temperature = config.temperature ?? 0.2;\n }\n\n async complete(prompt: string): Promise<string> {\n if (!this.config.apiKey) {\n throw new Error(\"NVIDIA NIM API key is required.\");\n }\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n const response = await fetch(this.endpoint, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.config.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n model: this.config.model,\n messages: [{ role: \"user\", content: prompt }],\n max_tokens: this.maxTokens,\n temperature: this.temperature,\n stream: false,\n }),\n signal: controller.signal,\n });\n\n const raw = await response.text();\n let payload: NimResponse | null = null;\n try {\n payload = JSON.parse(raw) as NimResponse;\n } catch {\n payload = null;\n }\n\n if (!response.ok) {\n throw new Error(normalizeNimError(response.status, raw, payload));\n }\n\n const content = payload?.choices?.[0]?.message?.content;\n const text =\n typeof content === \"string\"\n ? content\n : Array.isArray(content)\n ? content.map((entry) => entry.text || \"\").join(\"\\n\").trim()\n : \"\";\n\n if (!text) {\n throw new Error(\"NVIDIA NIM returned an empty completion.\");\n }\n\n return text;\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(\"NVIDIA NIM request timed out.\");\n }\n throw error;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n","import type { LlmAdapter, LlmProviderId } from \"../../types\";\n\nexport type FunctionAdapterConfig = {\n provider: LlmProviderId;\n complete: (prompt: string) => Promise<string>;\n};\n\nexport class FunctionLlmAdapter implements LlmAdapter {\n provider: LlmProviderId;\n\n constructor(private readonly config: FunctionAdapterConfig) {\n this.provider = config.provider;\n }\n\n complete(prompt: string): Promise<string> {\n return this.config.complete(prompt);\n }\n}\n","import type { SearchAdapter, SearchOptions, SearchResult } from \"../../types\";\n\nexport type HttpJsonSearchAdapterConfig = {\n endpoint: string;\n method?: \"GET\" | \"POST\";\n apiKey?: string;\n apiKeyHeader?: string;\n timeoutMs?: number;\n extraHeaders?: Record<string, string>;\n staticPayload?: Record<string, unknown>;\n};\n\ntype GenericSearchPayload = {\n results?: SearchResult[];\n items?: Array<{ title?: string; snippet?: string; url?: string; link?: string }>;\n error?: string;\n};\n\nconst sanitizeResults = (input: SearchResult[]) =>\n input.filter((item) => item.url && item.url !== \"#\" && item.title).map((item) => ({\n title: item.title,\n snippet: item.snippet || \"\",\n url: item.url,\n }));\n\nexport class HttpJsonSearchAdapter implements SearchAdapter {\n private readonly method: \"GET\" | \"POST\";\n private readonly timeoutMs: number;\n private readonly apiKeyHeader: string;\n\n constructor(private readonly config: HttpJsonSearchAdapterConfig) {\n this.method = config.method || \"POST\";\n this.timeoutMs = config.timeoutMs || 20000;\n this.apiKeyHeader = config.apiKeyHeader || \"Authorization\";\n }\n\n async search(query: string, options: SearchOptions): Promise<SearchResult[]> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...(this.config.extraHeaders || {}),\n };\n\n if (this.config.apiKey) {\n headers[this.apiKeyHeader] =\n this.apiKeyHeader.toLowerCase() === \"authorization\"\n ? `Bearer ${this.config.apiKey}`\n : this.config.apiKey;\n }\n\n const payload = {\n query,\n ...this.config.staticPayload,\n sites: options.sites || [],\n preferredSites: options.preferredSites || [],\n enforceSites: Boolean(options.enforceSites),\n forumHints: options.forumHints || [],\n };\n\n let response: Response;\n if (this.method === \"GET\") {\n const url = new URL(this.config.endpoint);\n url.searchParams.set(\"query\", query);\n response = await fetch(url.toString(), {\n method: \"GET\",\n headers,\n signal: controller.signal,\n });\n } else {\n response = await fetch(this.config.endpoint, {\n method: \"POST\",\n headers,\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n }\n\n const raw = await response.text();\n let parsed: GenericSearchPayload | null = null;\n try {\n parsed = JSON.parse(raw) as GenericSearchPayload;\n } catch {\n parsed = null;\n }\n\n if (!response.ok) {\n throw new Error(parsed?.error || raw || `Search adapter request failed (${response.status})`);\n }\n\n const byResults = Array.isArray(parsed?.results) ? parsed?.results : [];\n if (byResults.length > 0) {\n return sanitizeResults(byResults);\n }\n\n const byItems = Array.isArray(parsed?.items)\n ? parsed.items.map((item) => ({\n title: item.title || \"Untitled\",\n snippet: item.snippet || \"\",\n url: item.url || item.link || \"#\",\n }))\n : [];\n\n return sanitizeResults(byItems);\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(\"Search adapter timed out.\");\n }\n throw error;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,IAAM,mBAA6E;AAAA,EACjF,EAAE,SAAS,+BAA+B,QAAQ,cAAc,MAAM,SAAS;AAAA,EAC/E,EAAE,SAAS,yBAAyB,QAAQ,qBAAqB,MAAM,gBAAgB;AAAA,EACvF,EAAE,SAAS,2CAA2C,QAAQ,qBAAqB,MAAM,gBAAgB;AAAA,EACzG,EAAE,SAAS,6BAA6B,QAAQ,wBAAwB,MAAM,aAAa;AAAA,EAC3F,EAAE,SAAS,cAAc,QAAQ,aAAa,MAAM,QAAQ;AAAA,EAC5D,EAAE,SAAS,wBAAwB,QAAQ,cAAc,MAAM,SAAS;AAC1E;AAEA,IAAM,uBACJ;AAEF,IAAM,4BACJ;AAEK,IAAM,kBAAkB,CAAC,UAC9B,MAAM,KAAK,EAAE,YAAY,EAAE,QAAQ,gBAAgB,EAAE,EAAE,QAAQ,UAAU,EAAE;AAE7E,IAAM,SAAS,CAAC,UAAoB,MAAM,KAAK,IAAI,IAAI,MAAM,OAAO,OAAO,EAAE,IAAI,eAAe,CAAC,CAAC;AAE3F,IAAM,oBAAoB,CAAC,UAAkB;AAClD,QAAM,UAAU,MAAM,KAAK,MAAM,SAAS,sBAAsB,CAAC;AACjE,SAAO,OAAO,QAAQ,IAAI,CAAC,UAAU,MAAM,CAAC,CAAC,CAAC;AAChD;AAEO,IAAM,2BAA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;AAAA,IACvB;AAAA,IACA;AAAA,EACF;AAEA,SAAO,IAAI,uBAAuB,MAAM;AAC1C;","names":["unique"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
type DeepResearchDepth = "standard" | "deep" | "extreme";
|
|
2
|
+
type DeepResearchStage = "planning" | "retrieving" | "ranking" | "verifying" | "synthesizing" | "critiquing";
|
|
3
|
+
type LlmProviderId = "openrouter" | "nim" | "fallback";
|
|
4
|
+
type DeepResearchProgress = {
|
|
5
|
+
stage: DeepResearchStage;
|
|
6
|
+
message: string;
|
|
7
|
+
completed: number;
|
|
8
|
+
total: number;
|
|
9
|
+
};
|
|
10
|
+
type SearchResult = {
|
|
11
|
+
title: string;
|
|
12
|
+
snippet: string;
|
|
13
|
+
url: string;
|
|
14
|
+
};
|
|
15
|
+
type SearchConstraints = {
|
|
16
|
+
requiredDomains: string[];
|
|
17
|
+
preferredDomains: string[];
|
|
18
|
+
enforceRequiredDomains: boolean;
|
|
19
|
+
forumHints: string[];
|
|
20
|
+
};
|
|
21
|
+
type SearchOptions = {
|
|
22
|
+
sites?: string[];
|
|
23
|
+
preferredSites?: string[];
|
|
24
|
+
enforceSites?: boolean;
|
|
25
|
+
forumHints?: string[];
|
|
26
|
+
};
|
|
27
|
+
interface SearchAdapter {
|
|
28
|
+
search(query: string, options: SearchOptions): Promise<SearchResult[]>;
|
|
29
|
+
}
|
|
30
|
+
interface LlmAdapter {
|
|
31
|
+
provider: LlmProviderId;
|
|
32
|
+
complete(prompt: string): Promise<string>;
|
|
33
|
+
}
|
|
34
|
+
type PlannedQuery = {
|
|
35
|
+
query: string;
|
|
36
|
+
intent: string;
|
|
37
|
+
constrainedToDomain?: string;
|
|
38
|
+
};
|
|
39
|
+
type RankedSource = {
|
|
40
|
+
id: number;
|
|
41
|
+
title: string;
|
|
42
|
+
snippet: string;
|
|
43
|
+
url: string;
|
|
44
|
+
domain: string;
|
|
45
|
+
score: number;
|
|
46
|
+
retrievedFrom: string;
|
|
47
|
+
};
|
|
48
|
+
type ClaimCluster = {
|
|
49
|
+
claim: string;
|
|
50
|
+
citationIds: number[];
|
|
51
|
+
domains: string[];
|
|
52
|
+
confidence: "high" | "medium" | "low";
|
|
53
|
+
};
|
|
54
|
+
type DeepResearchRun = {
|
|
55
|
+
query: string;
|
|
56
|
+
depth: DeepResearchDepth;
|
|
57
|
+
plan: PlannedQuery[];
|
|
58
|
+
retrievalRounds: number;
|
|
59
|
+
rankedSources: RankedSource[];
|
|
60
|
+
claims: ClaimCluster[];
|
|
61
|
+
contradictions: string[];
|
|
62
|
+
unresolvedQuestions: string[];
|
|
63
|
+
promptContext: string;
|
|
64
|
+
finalAnswer: string;
|
|
65
|
+
synthesis: {
|
|
66
|
+
provider: LlmProviderId;
|
|
67
|
+
critiqueViolations: string[];
|
|
68
|
+
};
|
|
69
|
+
constraints: SearchConstraints;
|
|
70
|
+
sourcesForMessage: SearchResult[];
|
|
71
|
+
};
|
|
72
|
+
type DeepResearchRunOptions = {
|
|
73
|
+
depth?: DeepResearchDepth;
|
|
74
|
+
providerHint?: LlmProviderId;
|
|
75
|
+
constraints?: Partial<SearchConstraints>;
|
|
76
|
+
contextBlocks?: string[];
|
|
77
|
+
onProgress?: (progress: DeepResearchProgress) => void;
|
|
78
|
+
};
|
|
79
|
+
type DeepResearchEngineConfig = {
|
|
80
|
+
searchAdapter: SearchAdapter;
|
|
81
|
+
llmAdapters: Partial<Record<LlmProviderId, LlmAdapter>>;
|
|
82
|
+
defaultProvider: LlmProviderId;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
declare const normalizeDomain: (value: string) => string;
|
|
86
|
+
declare const extractSiteTokens: (query: string) => string[];
|
|
87
|
+
declare const extractSearchConstraints: (query: string) => SearchConstraints;
|
|
88
|
+
declare const domainMatches: (urlOrDomain: string, targetDomains: string[]) => boolean;
|
|
89
|
+
declare const mergeConstraints: (base: SearchConstraints, incoming?: Partial<SearchConstraints>) => SearchConstraints;
|
|
90
|
+
|
|
91
|
+
type TruthContractStrictness = "standard" | "strict";
|
|
92
|
+
type TruthContractCheck = {
|
|
93
|
+
passed: boolean;
|
|
94
|
+
violations: string[];
|
|
95
|
+
};
|
|
96
|
+
declare const buildTruthContractInstruction: (strictness: TruthContractStrictness) => string;
|
|
97
|
+
declare const evaluateTruthContract: (response: string, options?: {
|
|
98
|
+
requiresCitations?: boolean;
|
|
99
|
+
strictness?: TruthContractStrictness;
|
|
100
|
+
}) => TruthContractCheck;
|
|
101
|
+
|
|
102
|
+
declare class OpenDeepResearchEngine {
|
|
103
|
+
private readonly config;
|
|
104
|
+
private readonly resultCache;
|
|
105
|
+
constructor(config: DeepResearchEngineConfig);
|
|
106
|
+
private emit;
|
|
107
|
+
private buildPlan;
|
|
108
|
+
private buildRefinementQueries;
|
|
109
|
+
private retrieveWithCache;
|
|
110
|
+
private rank;
|
|
111
|
+
private verify;
|
|
112
|
+
private buildPromptContext;
|
|
113
|
+
private synthesize;
|
|
114
|
+
run(query: string, options?: DeepResearchRunOptions): Promise<DeepResearchRun>;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
type OpenRouterAdapterConfig = {
|
|
118
|
+
apiKey: string;
|
|
119
|
+
model: string;
|
|
120
|
+
endpoint?: string;
|
|
121
|
+
siteUrl?: string;
|
|
122
|
+
siteName?: string;
|
|
123
|
+
timeoutMs?: number;
|
|
124
|
+
};
|
|
125
|
+
declare class OpenRouterAdapter implements LlmAdapter {
|
|
126
|
+
private readonly config;
|
|
127
|
+
provider: "openrouter";
|
|
128
|
+
private readonly endpoint;
|
|
129
|
+
private readonly timeoutMs;
|
|
130
|
+
private readonly siteUrl;
|
|
131
|
+
private readonly siteName;
|
|
132
|
+
constructor(config: OpenRouterAdapterConfig);
|
|
133
|
+
complete(prompt: string): Promise<string>;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
type NimAdapterConfig = {
|
|
137
|
+
apiKey: string;
|
|
138
|
+
model: string;
|
|
139
|
+
endpoint?: string;
|
|
140
|
+
timeoutMs?: number;
|
|
141
|
+
maxTokens?: number;
|
|
142
|
+
temperature?: number;
|
|
143
|
+
};
|
|
144
|
+
declare class NimAdapter implements LlmAdapter {
|
|
145
|
+
private readonly config;
|
|
146
|
+
provider: "nim";
|
|
147
|
+
private readonly endpoint;
|
|
148
|
+
private readonly timeoutMs;
|
|
149
|
+
private readonly maxTokens;
|
|
150
|
+
private readonly temperature;
|
|
151
|
+
constructor(config: NimAdapterConfig);
|
|
152
|
+
complete(prompt: string): Promise<string>;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
type FunctionAdapterConfig = {
|
|
156
|
+
provider: LlmProviderId;
|
|
157
|
+
complete: (prompt: string) => Promise<string>;
|
|
158
|
+
};
|
|
159
|
+
declare class FunctionLlmAdapter implements LlmAdapter {
|
|
160
|
+
private readonly config;
|
|
161
|
+
provider: LlmProviderId;
|
|
162
|
+
constructor(config: FunctionAdapterConfig);
|
|
163
|
+
complete(prompt: string): Promise<string>;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
type HttpJsonSearchAdapterConfig = {
|
|
167
|
+
endpoint: string;
|
|
168
|
+
method?: "GET" | "POST";
|
|
169
|
+
apiKey?: string;
|
|
170
|
+
apiKeyHeader?: string;
|
|
171
|
+
timeoutMs?: number;
|
|
172
|
+
extraHeaders?: Record<string, string>;
|
|
173
|
+
staticPayload?: Record<string, unknown>;
|
|
174
|
+
};
|
|
175
|
+
declare class HttpJsonSearchAdapter implements SearchAdapter {
|
|
176
|
+
private readonly config;
|
|
177
|
+
private readonly method;
|
|
178
|
+
private readonly timeoutMs;
|
|
179
|
+
private readonly apiKeyHeader;
|
|
180
|
+
constructor(config: HttpJsonSearchAdapterConfig);
|
|
181
|
+
search(query: string, options: SearchOptions): Promise<SearchResult[]>;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
type CreateEngineOptions = {
|
|
185
|
+
searchAdapter: SearchAdapter;
|
|
186
|
+
defaultProvider?: LlmProviderId;
|
|
187
|
+
openRouter?: OpenRouterAdapterConfig;
|
|
188
|
+
nim?: NimAdapterConfig;
|
|
189
|
+
fallbackComplete?: (prompt: string) => Promise<string>;
|
|
190
|
+
};
|
|
191
|
+
declare const createOpenDeepResearchEngine: (options: CreateEngineOptions) => OpenDeepResearchEngine;
|
|
192
|
+
|
|
193
|
+
export { type ClaimCluster, type CreateEngineOptions, type DeepResearchDepth, type DeepResearchEngineConfig, type DeepResearchProgress, type DeepResearchRun, type DeepResearchRunOptions, type DeepResearchStage, type FunctionAdapterConfig, FunctionLlmAdapter, HttpJsonSearchAdapter, type HttpJsonSearchAdapterConfig, type LlmAdapter, type LlmProviderId, NimAdapter, type NimAdapterConfig, OpenDeepResearchEngine, OpenRouterAdapter, type OpenRouterAdapterConfig, type PlannedQuery, type RankedSource, type SearchAdapter, type SearchConstraints, type SearchOptions, type SearchResult, type TruthContractCheck, type TruthContractStrictness, buildTruthContractInstruction, createOpenDeepResearchEngine, domainMatches, evaluateTruthContract, extractSearchConstraints, extractSiteTokens, mergeConstraints, normalizeDomain };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
type DeepResearchDepth = "standard" | "deep" | "extreme";
|
|
2
|
+
type DeepResearchStage = "planning" | "retrieving" | "ranking" | "verifying" | "synthesizing" | "critiquing";
|
|
3
|
+
type LlmProviderId = "openrouter" | "nim" | "fallback";
|
|
4
|
+
type DeepResearchProgress = {
|
|
5
|
+
stage: DeepResearchStage;
|
|
6
|
+
message: string;
|
|
7
|
+
completed: number;
|
|
8
|
+
total: number;
|
|
9
|
+
};
|
|
10
|
+
type SearchResult = {
|
|
11
|
+
title: string;
|
|
12
|
+
snippet: string;
|
|
13
|
+
url: string;
|
|
14
|
+
};
|
|
15
|
+
type SearchConstraints = {
|
|
16
|
+
requiredDomains: string[];
|
|
17
|
+
preferredDomains: string[];
|
|
18
|
+
enforceRequiredDomains: boolean;
|
|
19
|
+
forumHints: string[];
|
|
20
|
+
};
|
|
21
|
+
type SearchOptions = {
|
|
22
|
+
sites?: string[];
|
|
23
|
+
preferredSites?: string[];
|
|
24
|
+
enforceSites?: boolean;
|
|
25
|
+
forumHints?: string[];
|
|
26
|
+
};
|
|
27
|
+
interface SearchAdapter {
|
|
28
|
+
search(query: string, options: SearchOptions): Promise<SearchResult[]>;
|
|
29
|
+
}
|
|
30
|
+
interface LlmAdapter {
|
|
31
|
+
provider: LlmProviderId;
|
|
32
|
+
complete(prompt: string): Promise<string>;
|
|
33
|
+
}
|
|
34
|
+
type PlannedQuery = {
|
|
35
|
+
query: string;
|
|
36
|
+
intent: string;
|
|
37
|
+
constrainedToDomain?: string;
|
|
38
|
+
};
|
|
39
|
+
type RankedSource = {
|
|
40
|
+
id: number;
|
|
41
|
+
title: string;
|
|
42
|
+
snippet: string;
|
|
43
|
+
url: string;
|
|
44
|
+
domain: string;
|
|
45
|
+
score: number;
|
|
46
|
+
retrievedFrom: string;
|
|
47
|
+
};
|
|
48
|
+
type ClaimCluster = {
|
|
49
|
+
claim: string;
|
|
50
|
+
citationIds: number[];
|
|
51
|
+
domains: string[];
|
|
52
|
+
confidence: "high" | "medium" | "low";
|
|
53
|
+
};
|
|
54
|
+
type DeepResearchRun = {
|
|
55
|
+
query: string;
|
|
56
|
+
depth: DeepResearchDepth;
|
|
57
|
+
plan: PlannedQuery[];
|
|
58
|
+
retrievalRounds: number;
|
|
59
|
+
rankedSources: RankedSource[];
|
|
60
|
+
claims: ClaimCluster[];
|
|
61
|
+
contradictions: string[];
|
|
62
|
+
unresolvedQuestions: string[];
|
|
63
|
+
promptContext: string;
|
|
64
|
+
finalAnswer: string;
|
|
65
|
+
synthesis: {
|
|
66
|
+
provider: LlmProviderId;
|
|
67
|
+
critiqueViolations: string[];
|
|
68
|
+
};
|
|
69
|
+
constraints: SearchConstraints;
|
|
70
|
+
sourcesForMessage: SearchResult[];
|
|
71
|
+
};
|
|
72
|
+
type DeepResearchRunOptions = {
|
|
73
|
+
depth?: DeepResearchDepth;
|
|
74
|
+
providerHint?: LlmProviderId;
|
|
75
|
+
constraints?: Partial<SearchConstraints>;
|
|
76
|
+
contextBlocks?: string[];
|
|
77
|
+
onProgress?: (progress: DeepResearchProgress) => void;
|
|
78
|
+
};
|
|
79
|
+
type DeepResearchEngineConfig = {
|
|
80
|
+
searchAdapter: SearchAdapter;
|
|
81
|
+
llmAdapters: Partial<Record<LlmProviderId, LlmAdapter>>;
|
|
82
|
+
defaultProvider: LlmProviderId;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
declare const normalizeDomain: (value: string) => string;
|
|
86
|
+
declare const extractSiteTokens: (query: string) => string[];
|
|
87
|
+
declare const extractSearchConstraints: (query: string) => SearchConstraints;
|
|
88
|
+
declare const domainMatches: (urlOrDomain: string, targetDomains: string[]) => boolean;
|
|
89
|
+
declare const mergeConstraints: (base: SearchConstraints, incoming?: Partial<SearchConstraints>) => SearchConstraints;
|
|
90
|
+
|
|
91
|
+
type TruthContractStrictness = "standard" | "strict";
|
|
92
|
+
type TruthContractCheck = {
|
|
93
|
+
passed: boolean;
|
|
94
|
+
violations: string[];
|
|
95
|
+
};
|
|
96
|
+
declare const buildTruthContractInstruction: (strictness: TruthContractStrictness) => string;
|
|
97
|
+
declare const evaluateTruthContract: (response: string, options?: {
|
|
98
|
+
requiresCitations?: boolean;
|
|
99
|
+
strictness?: TruthContractStrictness;
|
|
100
|
+
}) => TruthContractCheck;
|
|
101
|
+
|
|
102
|
+
declare class OpenDeepResearchEngine {
|
|
103
|
+
private readonly config;
|
|
104
|
+
private readonly resultCache;
|
|
105
|
+
constructor(config: DeepResearchEngineConfig);
|
|
106
|
+
private emit;
|
|
107
|
+
private buildPlan;
|
|
108
|
+
private buildRefinementQueries;
|
|
109
|
+
private retrieveWithCache;
|
|
110
|
+
private rank;
|
|
111
|
+
private verify;
|
|
112
|
+
private buildPromptContext;
|
|
113
|
+
private synthesize;
|
|
114
|
+
run(query: string, options?: DeepResearchRunOptions): Promise<DeepResearchRun>;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
type OpenRouterAdapterConfig = {
|
|
118
|
+
apiKey: string;
|
|
119
|
+
model: string;
|
|
120
|
+
endpoint?: string;
|
|
121
|
+
siteUrl?: string;
|
|
122
|
+
siteName?: string;
|
|
123
|
+
timeoutMs?: number;
|
|
124
|
+
};
|
|
125
|
+
declare class OpenRouterAdapter implements LlmAdapter {
|
|
126
|
+
private readonly config;
|
|
127
|
+
provider: "openrouter";
|
|
128
|
+
private readonly endpoint;
|
|
129
|
+
private readonly timeoutMs;
|
|
130
|
+
private readonly siteUrl;
|
|
131
|
+
private readonly siteName;
|
|
132
|
+
constructor(config: OpenRouterAdapterConfig);
|
|
133
|
+
complete(prompt: string): Promise<string>;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
type NimAdapterConfig = {
|
|
137
|
+
apiKey: string;
|
|
138
|
+
model: string;
|
|
139
|
+
endpoint?: string;
|
|
140
|
+
timeoutMs?: number;
|
|
141
|
+
maxTokens?: number;
|
|
142
|
+
temperature?: number;
|
|
143
|
+
};
|
|
144
|
+
declare class NimAdapter implements LlmAdapter {
|
|
145
|
+
private readonly config;
|
|
146
|
+
provider: "nim";
|
|
147
|
+
private readonly endpoint;
|
|
148
|
+
private readonly timeoutMs;
|
|
149
|
+
private readonly maxTokens;
|
|
150
|
+
private readonly temperature;
|
|
151
|
+
constructor(config: NimAdapterConfig);
|
|
152
|
+
complete(prompt: string): Promise<string>;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
type FunctionAdapterConfig = {
|
|
156
|
+
provider: LlmProviderId;
|
|
157
|
+
complete: (prompt: string) => Promise<string>;
|
|
158
|
+
};
|
|
159
|
+
declare class FunctionLlmAdapter implements LlmAdapter {
|
|
160
|
+
private readonly config;
|
|
161
|
+
provider: LlmProviderId;
|
|
162
|
+
constructor(config: FunctionAdapterConfig);
|
|
163
|
+
complete(prompt: string): Promise<string>;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
type HttpJsonSearchAdapterConfig = {
|
|
167
|
+
endpoint: string;
|
|
168
|
+
method?: "GET" | "POST";
|
|
169
|
+
apiKey?: string;
|
|
170
|
+
apiKeyHeader?: string;
|
|
171
|
+
timeoutMs?: number;
|
|
172
|
+
extraHeaders?: Record<string, string>;
|
|
173
|
+
staticPayload?: Record<string, unknown>;
|
|
174
|
+
};
|
|
175
|
+
declare class HttpJsonSearchAdapter implements SearchAdapter {
|
|
176
|
+
private readonly config;
|
|
177
|
+
private readonly method;
|
|
178
|
+
private readonly timeoutMs;
|
|
179
|
+
private readonly apiKeyHeader;
|
|
180
|
+
constructor(config: HttpJsonSearchAdapterConfig);
|
|
181
|
+
search(query: string, options: SearchOptions): Promise<SearchResult[]>;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
type CreateEngineOptions = {
|
|
185
|
+
searchAdapter: SearchAdapter;
|
|
186
|
+
defaultProvider?: LlmProviderId;
|
|
187
|
+
openRouter?: OpenRouterAdapterConfig;
|
|
188
|
+
nim?: NimAdapterConfig;
|
|
189
|
+
fallbackComplete?: (prompt: string) => Promise<string>;
|
|
190
|
+
};
|
|
191
|
+
declare const createOpenDeepResearchEngine: (options: CreateEngineOptions) => OpenDeepResearchEngine;
|
|
192
|
+
|
|
193
|
+
export { type ClaimCluster, type CreateEngineOptions, type DeepResearchDepth, type DeepResearchEngineConfig, type DeepResearchProgress, type DeepResearchRun, type DeepResearchRunOptions, type DeepResearchStage, type FunctionAdapterConfig, FunctionLlmAdapter, HttpJsonSearchAdapter, type HttpJsonSearchAdapterConfig, type LlmAdapter, type LlmProviderId, NimAdapter, type NimAdapterConfig, OpenDeepResearchEngine, OpenRouterAdapter, type OpenRouterAdapterConfig, type PlannedQuery, type RankedSource, type SearchAdapter, type SearchConstraints, type SearchOptions, type SearchResult, type TruthContractCheck, type TruthContractStrictness, buildTruthContractInstruction, createOpenDeepResearchEngine, domainMatches, evaluateTruthContract, extractSearchConstraints, extractSiteTokens, mergeConstraints, normalizeDomain };
|