chat-agent-toolkit 1.2.367 → 1.2.369

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.
Files changed (48) hide show
  1. package/dist/chat-agent-toolkit/src/tools/qwksearch-api-tools.d.ts +1 -1
  2. package/package.json +2 -2
  3. package/src/config/config-manager.d.ts +29 -0
  4. package/src/config/config-types.d.ts +58 -0
  5. package/src/config/environment-variables.d.ts +6 -0
  6. package/src/config/index.d.ts +18 -0
  7. package/src/config/language-models-database.d.ts +95 -0
  8. package/src/config/model-registry.d.ts +70 -0
  9. package/src/config/model-tester.d.ts +51 -0
  10. package/src/config/model-utils.d.ts +44 -0
  11. package/src/config/provider-ui-config.d.ts +13 -0
  12. package/src/connectors/index.d.ts +84 -0
  13. package/src/index.d.ts +27 -0
  14. package/src/mastra/agents.d.ts +78 -0
  15. package/src/mastra/evals.d.ts +63 -0
  16. package/src/mastra/index.d.ts +15 -0
  17. package/src/mastra/model-routing.d.ts +71 -0
  18. package/src/mastra/rag.d.ts +83 -0
  19. package/src/mastra/telemetry.d.ts +41 -0
  20. package/src/mastra/workflows.d.ts +85 -0
  21. package/src/memory/agent-memory-manager.d.ts +135 -0
  22. package/src/memory/index.d.ts +18 -0
  23. package/src/memory/mastra-integration.d.ts +161 -0
  24. package/src/memory/storage/drizzle-storage.d.ts +87 -0
  25. package/src/memory/storage/in-memory-storage.d.ts +86 -0
  26. package/src/memory/storage/storage-interface.d.ts +43 -0
  27. package/src/memory/types.d.ts +122 -0
  28. package/src/models/registry.d.ts +4 -0
  29. package/src/models/types.d.ts +4 -0
  30. package/src/prompts/index.d.ts +5 -0
  31. package/src/prompts/meta-search-types.d.ts +6 -0
  32. package/src/prompts/search-prompts.d.ts +25 -0
  33. package/src/tools/index.d.ts +13 -0
  34. package/src/tools/qwksearch-api-tools.d.ts +106 -0
  35. package/src/tools/qwksearch-mcp-tools.d.ts +26 -0
  36. package/src/tools/search/doc-utils.d.ts +49 -0
  37. package/src/tools/search/document.d.ts +14 -0
  38. package/src/tools/search/index.d.ts +13 -0
  39. package/src/tools/search/link-summarizer.d.ts +11 -0
  40. package/src/tools/search/meta-search-types.d.ts +56 -0
  41. package/src/tools/search/metaSearchAgent.d.ts +26 -0
  42. package/src/tools/search/search-handlers.d.ts +34 -0
  43. package/src/tools/search/suggestionGeneratorAgent.d.ts +19 -0
  44. package/src/tools/search/titleGeneratorAgent.d.ts +13 -0
  45. package/src/utils/chat-helpers.d.ts +10 -0
  46. package/src/utils/index.d.ts +5 -0
  47. package/src/utils/outputParser.d.ts +22 -0
  48. package/src/utils/provider-image-cropper.d.ts +127 -0
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Simple Memory Class
3
+ *
4
+ * Core memory management functionality with:
5
+ * - Message deduplication
6
+ * - Automatic summarization
7
+ * - Vector-based relevance search
8
+ * - Caching with TTL
9
+ * - Batch processing
10
+ * - Conflict resolution
11
+ */
12
+ import type { IMemoryStorage } from "./storage-interface";
13
+ import type { MemoryRecord, MemorySearchOptions, MemoryMetrics, MemoryOptions, MemoryContextOptions, MemoryType } from "../types";
14
+ export declare class SimpleMemory {
15
+ private userId;
16
+ private storage;
17
+ private maxMemories;
18
+ private summaryThreshold;
19
+ private cacheExpiry;
20
+ private batchSize;
21
+ private relevanceThreshold;
22
+ private enableVectorSearch;
23
+ private enableAutoSummarization;
24
+ private recentMessages;
25
+ private memoryCache;
26
+ private isProcessing;
27
+ private processingQueue;
28
+ private summarizeTimeout?;
29
+ private metrics;
30
+ /**
31
+ * Initialize memory system for a user
32
+ */
33
+ constructor(userId: string, storage: IMemoryStorage, options?: MemoryOptions);
34
+ /**
35
+ * Add a message to current session with intelligent deduplication
36
+ */
37
+ addMessage(role: "user" | "assistant", content: string, metadata?: Record<string, any>): boolean;
38
+ /**
39
+ * Debounced summarization to prevent excessive processing
40
+ */
41
+ private debouncedSummarize;
42
+ /**
43
+ * Store important facts with validation and conflict resolution
44
+ */
45
+ storeFact(content: string, importance?: number, category?: MemoryType, metadata?: Record<string, any>): Promise<string>;
46
+ /**
47
+ * Find similar facts using content similarity
48
+ */
49
+ private findSimilarFacts;
50
+ /**
51
+ * Enhanced memory recall with caching and vector search
52
+ */
53
+ recallRelevantMemories(query?: string, limit?: number, options?: MemorySearchOptions): Promise<MemoryRecord[]>;
54
+ /**
55
+ * Apply vector search to memories
56
+ */
57
+ private applyVectorSearch;
58
+ /**
59
+ * Update relevance scores for memories
60
+ */
61
+ private updateRelevanceScores;
62
+ /**
63
+ * Improved summarization with error handling and batch processing
64
+ */
65
+ summarizeAndStore(): Promise<boolean>;
66
+ /**
67
+ * Extract facts from conversation using LLM
68
+ */
69
+ private extractFactsFromConversation;
70
+ /**
71
+ * Process facts in batches to avoid overwhelming the database
72
+ */
73
+ private processFactsInBatches;
74
+ /**
75
+ * Clear cache utility
76
+ */
77
+ clearCache(): void;
78
+ /**
79
+ * Get memory context with better formatting and relevance
80
+ */
81
+ getMemoryContext(query?: string, includeRecent?: boolean, options?: MemoryContextOptions): Promise<string>;
82
+ /**
83
+ * Get performance metrics
84
+ */
85
+ getMetrics(): MemoryMetrics;
86
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Storage Interface
3
+ *
4
+ * Abstract interface for memory storage implementations.
5
+ * This allows swapping database backends without changing memory logic.
6
+ */
7
+ import type { MemoryRecord, MemoryType, MemorySearchOptions, MemoryUpdate } from "../types";
8
+ /**
9
+ * Storage interface that any database adapter must implement
10
+ */
11
+ export interface IMemoryStorage {
12
+ /**
13
+ * Insert a new memory record
14
+ */
15
+ insertMemory(userId: string, memoryType: MemoryType, content: string, importance: number, metadata?: Record<string, any>): Promise<string>;
16
+ /**
17
+ * Find memories by user ID and optional filters
18
+ */
19
+ findMemories(userId: string, query?: string, limit?: number, options?: MemorySearchOptions): Promise<MemoryRecord[]>;
20
+ /**
21
+ * Find similar memories based on content
22
+ */
23
+ findSimilarMemories(userId: string, content: string, limit?: number): Promise<MemoryRecord[]>;
24
+ /**
25
+ * Update a memory record
26
+ */
27
+ updateMemory(id: string, updates: MemoryUpdate): Promise<void>;
28
+ /**
29
+ * Delete a memory record
30
+ */
31
+ deleteMemory(id: string): Promise<void>;
32
+ /**
33
+ * Get memory by ID
34
+ */
35
+ getMemoryById(id: string): Promise<MemoryRecord | null>;
36
+ /**
37
+ * Batch update memories
38
+ */
39
+ batchUpdateMemories(updates: Array<{
40
+ id: string;
41
+ updates: MemoryUpdate;
42
+ }>): Promise<void>;
43
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Memory System Types and Constants
3
+ *
4
+ * Defines interfaces and configuration for the memory management system
5
+ */
6
+ /**
7
+ * Memory types for categorization
8
+ */
9
+ export declare const MEMORY_TYPES: {
10
+ readonly FACT: "fact";
11
+ readonly CONVERSATION: "conversation";
12
+ readonly PREFERENCE: "preference";
13
+ readonly PERSONAL: "personal";
14
+ readonly WORK: "work";
15
+ readonly MANUAL: "manual";
16
+ };
17
+ export type MemoryType = (typeof MEMORY_TYPES)[keyof typeof MEMORY_TYPES];
18
+ /**
19
+ * Configuration constants for memory management
20
+ */
21
+ export declare const MEMORY_CONFIG: {
22
+ readonly DEFAULT_MAX_MEMORIES: 100;
23
+ readonly DEFAULT_SUMMARY_THRESHOLD: 10;
24
+ readonly DEFAULT_CACHE_EXPIRY: number;
25
+ readonly DEFAULT_BATCH_SIZE: 5;
26
+ readonly DEFAULT_RELEVANCE_THRESHOLD: 0.3;
27
+ readonly DEFAULT_IMPORTANCE_RANGE: {
28
+ readonly min: 0;
29
+ readonly max: 10;
30
+ };
31
+ readonly DEFAULT_RATE_LIMIT: {
32
+ readonly requests: 10;
33
+ readonly windowMs: 60000;
34
+ };
35
+ readonly DEFAULT_TIMEOUT: 30000;
36
+ readonly VECTOR_SEARCH_ENABLED: true;
37
+ readonly AUTO_SUMMARIZATION_ENABLED: true;
38
+ };
39
+ /**
40
+ * Memory record structure
41
+ */
42
+ export interface MemoryRecord {
43
+ id: string;
44
+ user_id: string;
45
+ memory_type: MemoryType;
46
+ content: string;
47
+ importance: number;
48
+ access_count: number;
49
+ metadata?: Record<string, any>;
50
+ created_at: Date;
51
+ updated_at: Date;
52
+ relevance_score?: number;
53
+ }
54
+ /**
55
+ * Message structure for conversation tracking
56
+ */
57
+ export interface Message {
58
+ role: "user" | "assistant";
59
+ content: string;
60
+ timestamp: number;
61
+ metadata?: Record<string, any>;
62
+ }
63
+ /**
64
+ * Memory search options
65
+ */
66
+ export interface MemorySearchOptions {
67
+ minImportance?: number;
68
+ memoryType?: MemoryType;
69
+ includeMetadata?: boolean;
70
+ }
71
+ /**
72
+ * Memory update payload
73
+ */
74
+ export interface MemoryUpdate {
75
+ importance?: number;
76
+ access_count?: number | {
77
+ increment: number;
78
+ };
79
+ updated_at?: Date;
80
+ metadata?: Record<string, any>;
81
+ }
82
+ /**
83
+ * Memory context options
84
+ */
85
+ export interface MemoryContextOptions {
86
+ maxMemories?: number;
87
+ minImportance?: number;
88
+ }
89
+ /**
90
+ * Performance metrics
91
+ */
92
+ export interface MemoryMetrics {
93
+ cacheHits: number;
94
+ cacheMisses: number;
95
+ vectorSearches: number;
96
+ summarizations: number;
97
+ errors: number;
98
+ cacheSize: number;
99
+ recentMessagesCount: number;
100
+ isProcessing: boolean;
101
+ }
102
+ /**
103
+ * Memory initialization options
104
+ */
105
+ export interface MemoryOptions {
106
+ maxMemories?: number;
107
+ summaryThreshold?: number;
108
+ cacheExpiry?: number;
109
+ batchSize?: number;
110
+ relevanceThreshold?: number;
111
+ enableVectorSearch?: boolean;
112
+ enableAutoSummarization?: boolean;
113
+ }
114
+ /**
115
+ * Extracted fact structure
116
+ */
117
+ export interface ExtractedFact {
118
+ content: string;
119
+ importance?: number;
120
+ category?: MemoryType;
121
+ metadata?: Record<string, any>;
122
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * @fileoverview Re-export ModelRegistry from config directory
3
+ */
4
+ export { default } from "../config/model-registry";
@@ -0,0 +1,4 @@
1
+ /**
2
+ * @fileoverview Re-export model types from config directory
3
+ */
4
+ export type { Model, ConfigModelProvider, MinimalProvider } from "../config/config-types";
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @module agent-toolkit/prompts
3
+ * @description Prompt templates for AI agent tasks including web search and writing assistance.
4
+ */
5
+ export * from "./search-prompts";
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @module agent-toolkit/prompts/meta-search-types
3
+ * @description Shared types for search prompt few-shot examples.
4
+ */
5
+ /** A `[role, content]` tuple used for few-shot prompt examples. */
6
+ export type FewShotExample = [role: "user" | "assistant", content: string];
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @module agent-toolkit/prompts/search-prompts
3
+ * @description Prompt templates for web search and writing assistant agents.
4
+ */
5
+ import type { FewShotExample } from './meta-search-types';
6
+ export declare const webSearchRetrieverPrompt = "\nYou are an AI question rephraser. You will be given a conversation and a follow-up question, you will have to rephrase the follow up question so it is a standalone question and can be used by another LLM to search the web for information to answer it.\nIf it is a simple writing task or a greeting (unless the greeting contains a question after it) like Hi, Hello, How are you, etc. than a question then you need to return `not_needed` as the response (This is because the LLM won't need to search the web for finding information on this topic).\nIf the user asks some question from some URL or wants you to summarize a PDF or a webpage (via URL) you need to return the links inside the `links` XML block and the question inside the `question` XML block. If the user wants to you to summarize the webpage or the PDF you need to return `summarize` inside the `question` XML block in place of a question and the link to summarize in the `links` XML block.\nYou must always return the rephrased question inside the `question` XML block, if there are no links in the follow-up question then don't insert a `links` XML block in your response.\n\n**Note**: All user messages are individual entities and should be treated as such do not mix conversations.\n";
7
+ export declare const webSearchRetrieverFewShots: FewShotExample[];
8
+ /**
9
+ * Default template for generating follow-up question suggestions after an
10
+ * answer. Interpolated with `{maxQuestions}` and `{chat_history}`.
11
+ *
12
+ * Exported (rather than inlined in the suggestion agent) so the settings UI can
13
+ * show the live default in an editable textarea and users can override it.
14
+ */
15
+ export declare const followUpSuggestionsPrompt = "\nYou are an AI suggestion generator for an AI powered search engine. You will be given a conversation below. You need to generate {maxQuestions} suggestions based on the conversation. The suggestion should be relevant to the conversation that can be used by the user to ask the chat model for more information.\nYou need to make sure the suggestions are relevant to the conversation and are helpful to the user. Keep a note that the user might use these suggestions to ask a chat model for more information.\nMake sure the suggestions are medium in length and are informative and relevant to the conversation.\n\nProvide these suggestions separated by newlines between the XML tags <suggestions> and </suggestions>. For example:\n\n<suggestions>\nTell me more about SpaceX and their recent projects\nWhat is the latest news on SpaceX?\nWho is the CEO of SpaceX?\n</suggestions>\n\nConversation:\n{chat_history}\n";
16
+ export declare const webSearchResponsePrompt = "\n You are QwkSearch, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses.\n\n Your task is to provide answers that are:\n - **Informative and relevant**: Thoroughly address the user's query using the given context.\n - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically.\n - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights.\n - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included.\n - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable.\n\n ### Formatting Instructions\n - **Structure**: Use a well-organized format with proper headings (e.g., \"## Example heading 1\" or \"## Example heading 2\"). Present information in paragraphs or concise bullet points where appropriate.\n - **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience.\n - **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability.\n - **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience.\n - **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title.\n - **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate.\n\n ### Citation Requirements\n - Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided `context`.\n - Integrate citations naturally at the end of sentences or clauses as appropriate. For example, \"The Eiffel Tower is one of the most visited landmarks in the world[1].\"\n - Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context.\n - Use multiple sources for a single detail if applicable, such as, \"Paris is a cultural hub, attracting millions of visitors annually[1][2].\"\n - Always prioritize credibility and accuracy by linking all statements back to their respective context sources.\n - Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation.\n\n ### Special Instructions\n - If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity.\n - If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search.\n - If no relevant information is found, say: \"Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?\" Be transparent about limitations and suggest alternatives or ways to reframe the query.\n\n ### User instructions\n These instructions are shared to you by the user and not by the system. You will have to follow them but give them less priority than the above instructions. If the user has provided specific instructions or preferences, incorporate them into your response while adhering to the overall guidelines.\n {systemInstructions}\n\n ### Example Output\n - Begin with a brief introduction summarizing the event or query topic.\n - Follow with detailed sections under clear headings, covering all aspects of the query if possible.\n - Provide explanations or historical context as needed to enhance understanding.\n - End with a conclusion or overall perspective if relevant.\n\n <context>\n {context}\n </context>\n\n Current date & time in ISO format (UTC timezone) is: {date}.\n";
17
+ export declare const writingAssistantPrompt = "\nYou are QwkSearch, an AI model who is expert at searching the web and answering user's queries. You are currently set on focus mode 'Writing Assistant', this means you will be helping the user write a response to a given query.\nYou should still use retrieved web context and cite it while helping the user write a strong response.\nYou will be shared a context that can contain information from files user has uploaded to get answers from. You will have to generate answers upon that.\n\nYou have to cite the answer using [number] notation. You must cite the sentences with their relevant context number. You must cite each and every part of the answer so the user can know where the information is coming from.\nPlace these citations at the end of that particular sentence. You can cite the same sentence multiple times if it is relevant to the user's query like [number1][number2].\nHowever you do not need to cite it using the same number. You can use different numbers to cite the same sentence multiple times. The number refers to the number of the search result (passed in the context) used to generate that part of the answer.\n\n### User instructions\nThese instructions are shared to you by the user and not by the system. You will have to follow them but give them less priority than the above instructions. If the user has provided specific instructions or preferences, incorporate them into your response while adhering to the overall guidelines.\n{systemInstructions}\n\n<context>\n{context}\n</context>\n";
18
+ declare const _default: {
19
+ webSearchResponsePrompt: string;
20
+ webSearchRetrieverPrompt: string;
21
+ webSearchRetrieverFewShots: FewShotExample[];
22
+ writingAssistantPrompt: string;
23
+ followUpSuggestionsPrompt: string;
24
+ };
25
+ export default _default;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @fileoverview Agent Tools Module
3
+ *
4
+ * Exports tool definitions for QwkSearch API integration including web search,
5
+ * content extraction, and AI response generation. Tools are automatically
6
+ * attached to agents when declared in prompt templates.
7
+ *
8
+ * @module tools
9
+ * @author ai-research-agent contributors
10
+ */
11
+ export { AGENT_TOOLS } from "./qwksearch-api-tools";
12
+ export { QwkSearchMCPSession, getQwkSearchTools } from "./qwksearch-mcp-tools";
13
+ export * from "./search";
@@ -0,0 +1,106 @@
1
+ /**
2
+ * @fileoverview Specialized tools for AI agents to interact with the QwkSearch API.
3
+ * Provides web search, content extraction, and AI response generation.
4
+ */
5
+ import { z } from "zod";
6
+ /**
7
+ * List of tools available for agent usage, including their schemas and implementation.
8
+ */
9
+ export declare const AGENT_TOOLS: ({
10
+ name: string;
11
+ description: string;
12
+ schema: z.ZodObject<{
13
+ query: z.ZodString;
14
+ category: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
15
+ files: "files";
16
+ general: "general";
17
+ images: "images";
18
+ it: "it";
19
+ news: "news";
20
+ science: "science";
21
+ videos: "videos";
22
+ }>>>;
23
+ recency: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
24
+ day: "day";
25
+ month: "month";
26
+ none: "none";
27
+ week: "week";
28
+ year: "year";
29
+ }>>>;
30
+ page: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
31
+ language: z.ZodDefault<z.ZodOptional<z.ZodString>>;
32
+ public: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
33
+ timeout: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
34
+ baseURL: z.ZodOptional<z.ZodString>;
35
+ apiKey: z.ZodOptional<z.ZodString>;
36
+ }, z.core.$strip>;
37
+ func: ({ query, category, recency, page, language, public: isPublic, timeout, baseURL, apiKey }: {
38
+ apiKey: any;
39
+ baseURL: any;
40
+ category?: string;
41
+ language?: string;
42
+ page?: number;
43
+ public?: boolean;
44
+ query: any;
45
+ recency?: string;
46
+ timeout?: number;
47
+ }) => Promise<string>;
48
+ } | {
49
+ name: string;
50
+ description: string;
51
+ schema: z.ZodObject<{
52
+ url: z.ZodString;
53
+ images: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
54
+ links: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
55
+ formatting: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
56
+ absoluteURLs: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
57
+ timeout: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
58
+ baseURL: z.ZodOptional<z.ZodString>;
59
+ apiKey: z.ZodOptional<z.ZodString>;
60
+ }, z.core.$strip>;
61
+ func: ({ url, images, links, formatting, absoluteURLs, timeout, baseURL, apiKey }: {
62
+ absoluteURLs?: boolean;
63
+ apiKey: any;
64
+ baseURL: any;
65
+ formatting?: boolean;
66
+ images?: boolean;
67
+ links?: boolean;
68
+ timeout?: number;
69
+ url: any;
70
+ }) => Promise<string>;
71
+ } | {
72
+ name: string;
73
+ description: string;
74
+ schema: z.ZodObject<{
75
+ url: z.ZodString;
76
+ blockImages: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
77
+ wait: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
78
+ timeout: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
79
+ waitUntil: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
80
+ domcontentloaded: "domcontentloaded";
81
+ load: "load";
82
+ networkidle0: "networkidle0";
83
+ networkidle2: "networkidle2";
84
+ }>>>;
85
+ bypassCaptcha: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
86
+ sessionId: z.ZodDefault<z.ZodOptional<z.ZodString>>;
87
+ format: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
88
+ html: "html";
89
+ json: "json";
90
+ }>>>;
91
+ scraperUrl: z.ZodOptional<z.ZodString>;
92
+ scraperApiKey: z.ZodOptional<z.ZodString>;
93
+ }, z.core.$strip>;
94
+ func: ({ url, blockImages, wait, timeout, waitUntil, bypassCaptcha, sessionId, format, scraperUrl, scraperApiKey }: {
95
+ blockImages?: boolean;
96
+ bypassCaptcha?: boolean;
97
+ format?: string;
98
+ scraperApiKey: any;
99
+ scraperUrl: any;
100
+ sessionId?: string;
101
+ timeout?: number;
102
+ url: any;
103
+ wait?: number;
104
+ waitUntil?: string;
105
+ }) => Promise<string>;
106
+ })[];
@@ -0,0 +1,26 @@
1
+ import type { ToolSet } from "ai";
2
+ export interface QwkSearchMCPConfig {
3
+ command?: string;
4
+ args?: string[];
5
+ env?: Record<string, string>;
6
+ }
7
+ /**
8
+ * Long-lived MCP session for QwkSearch tools.
9
+ * Spawns a local MCP server process and keeps it alive across tool calls.
10
+ */
11
+ export declare class QwkSearchMCPSession {
12
+ private client;
13
+ private config;
14
+ constructor(config?: QwkSearchMCPConfig);
15
+ getTools(): Promise<ToolSet>;
16
+ close(): Promise<void>;
17
+ }
18
+ /**
19
+ * One-shot helper to get QwkSearch MCP tools.
20
+ * Creates a session, fetches tools, and returns them.
21
+ * Caller should close the returned session when done.
22
+ */
23
+ export declare function getQwkSearchTools(config?: QwkSearchMCPConfig): Promise<{
24
+ tools: ToolSet;
25
+ session: QwkSearchMCPSession;
26
+ }>;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @module research/search/doc-utils
3
+ * @description Document utilities: fallback docs, reranking, and formatting.
4
+ */
5
+ import type { Document } from "./document";
6
+ export interface R2CredentialsInput {
7
+ accountId: string;
8
+ accessKeyId: string;
9
+ secretAccessKey: string;
10
+ bucket: string;
11
+ }
12
+ export declare function buildFallbackDocs(query: string): Document[];
13
+ export declare function normalizeSourcesOutput(output: unknown, query: string): Document[];
14
+ /** The payload resolved for an uploaded fileId. */
15
+ export interface LoadedUpload {
16
+ title: string;
17
+ content: string;
18
+ /** MIME type for image uploads (e.g. `"image/png"`). */
19
+ mediaType?: string;
20
+ /** `data:`/`http(s)` URL of an image upload, passed to the LLM as image content. */
21
+ image?: string;
22
+ }
23
+ /** An image attachment resolved from an uploaded fileId. */
24
+ export interface UploadImageAttachment {
25
+ mediaType: string;
26
+ /** `data:`/`http(s)` URL of the image, ready for an AI SDK image content part. */
27
+ image: string;
28
+ }
29
+ /**
30
+ * Resolves an uploaded fileId to its extracted payload. Hosts register a loader
31
+ * (e.g. reading the native R2 binding) so the search pipeline does not depend
32
+ * on filesystem or credential-based access. Image uploads additionally carry
33
+ * `mediaType` and `image` so they can be passed to the LLM directly.
34
+ */
35
+ export type UploadFileLoader = (fileId: string) => Promise<LoadedUpload | null>;
36
+ /**
37
+ * Registers the loader used by {@link rerankDocs} to resolve uploaded
38
+ * fileIds to extracted content. The registered loader takes precedence over
39
+ * the S3-credentials fallback.
40
+ */
41
+ export declare function registerUploadFileLoader(loader: UploadFileLoader): void;
42
+ /**
43
+ * Resolves image attachments for the given uploaded fileIds so they can be
44
+ * passed to the LLM as image content parts. Non-image uploads (documents) and
45
+ * images stored without inline data are skipped.
46
+ */
47
+ export declare function loadUploadImages(fileIds: string[], r2Credentials?: R2CredentialsInput): Promise<UploadImageAttachment[]>;
48
+ export declare function rerankDocs(query: string, docs: Document[], fileIds: string[], optimizationMode: "speed" | "balanced" | "quality", r2Credentials?: R2CredentialsInput): Promise<Document[]>;
49
+ export declare function processDocs(docs: Document[]): string;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @module research/search/document
3
+ * @description Minimal document shape shared across the search pipeline.
4
+ * A document is a chunk of page content plus citation metadata (title, url, source, etc.).
5
+ */
6
+ export interface Document<Metadata extends Record<string, any> = Record<string, any>> {
7
+ pageContent: string;
8
+ metadata: Metadata;
9
+ }
10
+ /**
11
+ * Splits text into overlapping chunks on whitespace boundaries.
12
+ * Default chunkSize 1000, chunkOverlap 200.
13
+ */
14
+ export declare function splitTextIntoChunks(text: string, chunkSize?: number, chunkOverlap?: number): string[];
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @module agent-toolkit/tools/search
3
+ * @description Meta search agent tools for AI-powered web search and research
4
+ */
5
+ export { default as MetaSearchAgent } from "./metaSearchAgent";
6
+ export type { MetaSearchAgentType, Config, ChatTurnMessage, SearchingEvent, FewShotExample } from "./meta-search-types";
7
+ export { searchHandlers, createSearchHandlers } from "./search-handlers";
8
+ export { default as generateSuggestions } from "./suggestionGeneratorAgent";
9
+ export { groupAndSummarizeDocs } from "./link-summarizer";
10
+ export type { Document } from "./document";
11
+ export { splitTextIntoChunks } from "./document";
12
+ export { buildFallbackDocs, rerankDocs, processDocs, normalizeSourcesOutput, registerUploadFileLoader, loadUploadImages } from "./doc-utils";
13
+ export type { UploadFileLoader, LoadedUpload, UploadImageAttachment } from "./doc-utils";
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @module research/search/link-summarizer
3
+ * @description Groups link documents by URL then summarizes each group with an LLM.
4
+ */
5
+ import { type LanguageModel } from "ai";
6
+ import type { Document } from "./document";
7
+ /**
8
+ * Groups fetched link documents by URL (max 10 chunks per URL), then
9
+ * summarizes each group with the LLM in parallel.
10
+ */
11
+ export declare function groupAndSummarizeDocs(llm: LanguageModel, linkDocs: Document[], question: string): Promise<Document[]>;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @module research/search/meta-search-types
3
+ * @description Shared types for the MetaSearchAgent.
4
+ */
5
+ import type { LanguageModel } from "ai";
6
+ import type EventEmitter from "events";
7
+ /** A single conversation turn, matching the Vercel AI SDK message shape. */
8
+ export interface ChatTurnMessage {
9
+ role: "user" | "assistant" | "system";
10
+ content: string;
11
+ }
12
+ /** A `[role, content]` tuple used for few-shot prompt examples. */
13
+ export type FewShotExample = [role: "user" | "assistant", content: string];
14
+ export interface MetaSearchAgentType {
15
+ searchAndAnswer: (message: string, history: ChatTurnMessage[], llm: LanguageModel, optimizationMode: "speed" | "balanced" | "quality", fileIds: string[], systemInstructions: string, category?: string, sourceExtractionEnabled?: boolean, thinkingTimeLimit?: number,
16
+ /** User-authored replacement for the focus mode's query-expansion prompt. */
17
+ queryExpansionPrompt?: string) => Promise<EventEmitter>;
18
+ }
19
+ /** Emitted on the EventEmitter data channel to report live search progress. */
20
+ export interface SearchingEvent {
21
+ query: string;
22
+ /** Display label shown in the UI (e.g. "Academic · max 10"). */
23
+ category?: string;
24
+ status: "running" | "done";
25
+ }
26
+ export interface Config {
27
+ searchWeb: boolean;
28
+ rerank: boolean;
29
+ rerankThreshold: number;
30
+ queryGeneratorPrompt: string;
31
+ queryGeneratorFewShots: FewShotExample[];
32
+ responsePrompt: string;
33
+ activeEngines: string[];
34
+ /** Optional: Function to fetch documents from URLs */
35
+ getDocumentsFromLinks?: (options: {
36
+ links: string[];
37
+ }) => Promise<any[]>;
38
+ /** Optional: Function to search via SearXNG */
39
+ searchSearxng?: (query: string, options: any) => Promise<{
40
+ results: any[];
41
+ suggestions: string[];
42
+ }>;
43
+ /** Optional: Function to search via Tavily */
44
+ searchTavily?: (query: string, options: any) => Promise<{
45
+ results: any[];
46
+ suggestions: string[];
47
+ }>;
48
+ /** Optional: Function to check if Tavily is configured */
49
+ isTavilyConfigured?: () => boolean;
50
+ /** Optional: Function to scrape a URL */
51
+ scrapeURL?: (url: string, options: any) => Promise<string>;
52
+ }
53
+ export type BasicChainInput = {
54
+ chat_history: ChatTurnMessage[];
55
+ query: string;
56
+ };
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @fileoverview Orchestrator for complex research queries.
3
+ * Manages query expansion, web search execution, and result synthesis using
4
+ * LLMs through the Vercel AI SDK (generateText/streamText).
5
+ */
6
+ import { type LanguageModel } from "ai";
7
+ import EventEmitter from "events";
8
+ import type { Config, ChatTurnMessage, MetaSearchAgentType } from "./meta-search-types";
9
+ export type { MetaSearchAgentType, Config } from "./meta-search-types";
10
+ declare class MetaSearchAgent implements MetaSearchAgentType {
11
+ private config;
12
+ constructor(config: Config);
13
+ /**
14
+ * Rephrases the user's query into a standalone search question (and any
15
+ * URLs to summarize), runs the web search, and returns the documents to
16
+ * use as answer context.
17
+ */
18
+ private retrieveSearchDocs;
19
+ /**
20
+ * Runs the full search-and-answer pipeline, emitting "sources",
21
+ * "response", "searching", "end", and "error" events on the emitter.
22
+ */
23
+ private runPipeline;
24
+ searchAndAnswer(message: string, history: ChatTurnMessage[], llm: LanguageModel, optimizationMode: "speed" | "balanced" | "quality", fileIds: string[], systemInstructions: string, category?: string, sourceExtractionEnabled?: boolean, thinkingTimeLimit?: number, queryExpansionPrompt?: string): Promise<EventEmitter<any>>;
25
+ }
26
+ export default MetaSearchAgent;