@xache/langchain 0.2.3 → 0.4.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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/memory.ts","../src/chat_history.ts","../src/retriever.ts","../src/extraction.ts","../src/collective.ts","../src/reputation.ts"],"sourcesContent":["/**\n * @xache/langchain\n * LangChain.js integration for Xache Protocol\n *\n * Drop-in memory, retrieval, and collective intelligence with verifiable receipts.\n *\n * @example\n * ```typescript\n * // One-line memory replacement\n * import { XacheMemory } from '@xache/langchain';\n *\n * const memory = new XacheMemory({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * });\n *\n * // Use with any LangChain chain\n * const chain = new ConversationChain({ llm, memory });\n * ```\n *\n * @packageDocumentation\n */\n\n// Memory\nexport { XacheMemory, XacheConversationBufferMemory } from './memory';\nexport type { XacheMemoryConfig } from './memory';\n\n// Chat History\nexport { XacheChatMessageHistory } from './chat_history';\nexport type { XacheChatMessageHistoryConfig } from './chat_history';\n\n// Retrieval\nexport { XacheRetriever } from './retriever';\nexport type { XacheRetrieverConfig } from './retriever';\n\n// Extraction\nexport { XacheExtractor } from './extraction';\nexport type {\n XacheExtractorConfig,\n ExtractedMemory,\n ExtractionResult,\n} from './extraction';\n\n// Collective Intelligence\nexport {\n createCollectiveContributeTool,\n createCollectiveQueryTool,\n XacheCollectiveContributeTool,\n XacheCollectiveQueryTool,\n} from './collective';\nexport type { CollectiveToolConfig } from './collective';\n\n// Reputation\nexport {\n createReputationTool,\n XacheReputationTool,\n XacheReputationChecker,\n} from './reputation';\nexport type { ReputationToolConfig, ReputationResult } from './reputation';\n","/**\n * Xache Memory for LangChain.js\n * Drop-in replacement for ConversationBufferMemory with verifiable receipts\n */\n\nimport { BaseMemory, InputValues, OutputValues, MemoryVariables } from '@langchain/core/memory';\nimport { XacheChatMessageHistory, XacheChatMessageHistoryConfig } from './chat_history';\n\nexport interface XacheMemoryConfig extends XacheChatMessageHistoryConfig {\n /** Memory key for input (default: 'input') */\n inputKey?: string;\n /** Memory key for output (default: 'output') */\n outputKey?: string;\n /** Key for returning memory (default: 'history') */\n memoryKey?: string;\n /** Return messages as list vs string */\n returnMessages?: boolean;\n}\n\n/**\n * Drop-in replacement for LangChain memory with Xache storage.\n *\n * Provides persistent, verifiable memory that survives across sessions.\n *\n * @example\n * ```typescript\n * import { XacheMemory } from '@xache/langchain';\n * import { ChatOpenAI } from '@langchain/openai';\n * import { ConversationChain } from 'langchain/chains';\n *\n * const memory = new XacheMemory({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * });\n *\n * const chain = new ConversationChain({\n * llm: new ChatOpenAI(),\n * memory,\n * });\n *\n * await chain.call({ input: 'Hello!' });\n * ```\n */\nexport class XacheMemory extends BaseMemory {\n lc_namespace = ['xache', 'memory'];\n\n private chatHistory: XacheChatMessageHistory;\n private inputKey: string;\n private outputKey: string;\n private memoryKey: string;\n private returnMessages: boolean;\n\n constructor(config: XacheMemoryConfig) {\n super();\n this.chatHistory = new XacheChatMessageHistory(config);\n this.inputKey = config.inputKey || 'input';\n this.outputKey = config.outputKey || 'output';\n this.memoryKey = config.memoryKey || 'history';\n this.returnMessages = config.returnMessages ?? false;\n }\n\n get memoryKeys(): string[] {\n return [this.memoryKey];\n }\n\n /**\n * Load memory variables\n */\n async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n const messages = await this.chatHistory.getMessages();\n\n if (this.returnMessages) {\n return { [this.memoryKey]: messages };\n }\n\n // Convert to string format\n const history = messages\n .map((m) => {\n const role = m._getType() === 'human' ? 'Human' : 'AI';\n const content =\n typeof m.content === 'string' ? m.content : JSON.stringify(m.content);\n return `${role}: ${content}`;\n })\n .join('\\n');\n\n return { [this.memoryKey]: history };\n }\n\n /**\n * Save context from this conversation to buffer\n */\n async saveContext(\n inputValues: InputValues,\n outputValues: OutputValues\n ): Promise<void> {\n const input = inputValues[this.inputKey];\n const output = outputValues[this.outputKey];\n\n if (input) {\n await this.chatHistory.addUserMessage(String(input));\n }\n\n if (output) {\n await this.chatHistory.addAIMessage(String(output));\n }\n }\n\n /**\n * Clear memory contents\n */\n async clear(): Promise<void> {\n await this.chatHistory.clear();\n }\n}\n\n/**\n * Extended memory with conversation buffer capabilities\n */\nexport class XacheConversationBufferMemory extends XacheMemory {\n lc_namespace = ['xache', 'memory', 'buffer'];\n}\n","/**\n * Xache Chat Message History for LangChain.js\n * Persistent message storage with cryptographic receipts\n */\n\nimport { BaseListChatMessageHistory } from '@langchain/core/chat_history';\nimport {\n BaseMessage,\n HumanMessage,\n AIMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport { XacheClient, DID } from '@xache/sdk';\nimport { randomUUID } from 'crypto';\n\nexport interface XacheChatMessageHistoryConfig {\n /** Wallet address for authentication */\n walletAddress: string;\n /** Private key for signing */\n privateKey: string;\n /** Session ID to group messages */\n sessionId?: string;\n /** API URL (defaults to https://api.xache.xyz) */\n apiUrl?: string;\n /** Chain: 'base' or 'solana' */\n chain?: 'base' | 'solana';\n /** Maximum messages to load (default: 1000, set to -1 for unlimited) */\n maxMessages?: number;\n /** Page size for loading messages (default: 100) */\n pageSize?: number;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Enable debug logging */\n debug?: boolean;\n}\n\n/**\n * Chat message history backed by Xache Protocol.\n *\n * Messages are stored with cryptographic receipts and can persist\n * across sessions.\n *\n * @example\n * ```typescript\n * import { XacheChatMessageHistory } from '@xache/langchain';\n *\n * const history = new XacheChatMessageHistory({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * sessionId: 'unique-session-id',\n * });\n *\n * await history.addUserMessage('Hello!');\n * await history.addAIMessage('Hi there!');\n *\n * const messages = await history.getMessages();\n * ```\n */\nexport class XacheChatMessageHistory extends BaseListChatMessageHistory {\n lc_namespace = ['xache', 'chat_history'];\n\n private client: XacheClient;\n private sessionId: string;\n private messages: BaseMessage[] = [];\n private initialized = false;\n private maxMessages: number;\n private pageSize: number;\n\n constructor(config: XacheChatMessageHistoryConfig) {\n super();\n\n const chainPrefix = config.chain === 'solana' ? 'sol' : 'evm';\n const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}` as DID;\n\n this.client = new XacheClient({\n apiUrl: config.apiUrl || 'https://api.xache.xyz',\n did,\n privateKey: config.privateKey,\n timeout: config.timeout,\n debug: config.debug,\n });\n\n // Use UUID for collision-resistant session IDs\n this.sessionId = config.sessionId || `langchain-${randomUUID()}`;\n this.maxMessages = config.maxMessages ?? 1000;\n this.pageSize = config.pageSize ?? 100;\n }\n\n /**\n * Get all messages in the history\n */\n async getMessages(): Promise<BaseMessage[]> {\n if (!this.initialized) {\n await this.loadMessages();\n }\n return this.messages;\n }\n\n /**\n * Add a message to the history\n */\n async addMessage(message: BaseMessage): Promise<void> {\n this.messages.push(message);\n\n const role = this.getMessageRole(message);\n const content =\n typeof message.content === 'string'\n ? message.content\n : JSON.stringify(message.content);\n\n await this.client.memory.store({\n data: {\n role,\n content,\n sessionId: this.sessionId,\n timestamp: Date.now(),\n },\n storageTier: 'hot',\n context: `chat:${this.sessionId}`,\n tags: ['chat', 'message', role],\n metadata: {\n sessionId: this.sessionId,\n role,\n },\n });\n }\n\n /**\n * Add a user message\n */\n async addUserMessage(message: string): Promise<void> {\n await this.addMessage(new HumanMessage(message));\n }\n\n /**\n * Add an AI message\n */\n async addAIMessage(message: string): Promise<void> {\n await this.addMessage(new AIMessage(message));\n }\n\n /**\n * Clear all messages from history\n */\n async clear(): Promise<void> {\n this.messages = [];\n // Note: Xache doesn't support deletion - messages remain for audit trail\n // We only clear the local cache\n }\n\n /**\n * Load messages from Xache storage with pagination support\n */\n private async loadMessages(): Promise<void> {\n try {\n const allMemories: Array<{ storage_key: string; created_at?: string }> = [];\n let offset = 0;\n const effectiveMax = this.maxMessages === -1 ? Infinity : this.maxMessages;\n\n // Paginate through all messages\n while (allMemories.length < effectiveMax) {\n const result = await this.client.memory.list({\n context: `chat:${this.sessionId}`,\n limit: Math.min(this.pageSize, effectiveMax - allMemories.length),\n offset,\n });\n\n const memories = Array.isArray(result?.memories) ? result.memories : [];\n if (memories.length === 0) break;\n\n allMemories.push(...memories);\n offset += memories.length;\n\n // If we got less than pageSize, we've reached the end\n if (memories.length < this.pageSize) break;\n }\n\n // Sort by timestamp\n const sortedMemories = [...allMemories].sort((a, b) => {\n const tsA = new Date(a.created_at || 0).getTime();\n const tsB = new Date(b.created_at || 0).getTime();\n return tsA - tsB;\n });\n\n // For each memory, we need to retrieve the full content\n this.messages = [];\n for (const m of sortedMemories) {\n try {\n const full = await this.client.memory.retrieve({\n storageKey: m.storage_key,\n });\n const data = full.data as { role?: string; content?: string };\n if (data && data.content) {\n switch (data.role) {\n case 'human':\n case 'user':\n this.messages.push(new HumanMessage(data.content));\n break;\n case 'ai':\n case 'assistant':\n this.messages.push(new AIMessage(data.content));\n break;\n case 'system':\n this.messages.push(new SystemMessage(data.content));\n break;\n default:\n this.messages.push(new HumanMessage(data.content));\n }\n }\n } catch (error) {\n // Skip malformed messages but log in debug\n console.debug?.(`[XacheChatMessageHistory] Failed to parse message: ${(error as Error).message}`);\n }\n }\n\n this.initialized = true;\n } catch (error) {\n // If retrieval fails (e.g., no memories yet), start fresh\n // This is expected for new sessions\n console.debug?.(`[XacheChatMessageHistory] No existing messages found: ${(error as Error).message}`);\n this.messages = [];\n this.initialized = true;\n }\n }\n\n private getMessageRole(message: BaseMessage): string {\n if (message instanceof HumanMessage) return 'human';\n if (message instanceof AIMessage) return 'ai';\n if (message instanceof SystemMessage) return 'system';\n return 'unknown';\n }\n}\n","/**\n * Xache Retriever for LangChain.js\n * Memory retrieval for RAG pipelines with verifiable receipts\n */\n\nimport { BaseRetriever, BaseRetrieverInput } from '@langchain/core/retrievers';\nimport { Document } from '@langchain/core/documents';\nimport { CallbackManagerForRetrieverRun } from '@langchain/core/callbacks/manager';\nimport { XacheClient, DID } from '@xache/sdk';\n\nexport interface XacheRetrieverConfig extends BaseRetrieverInput {\n /** Wallet address for authentication */\n walletAddress: string;\n /** Private key for signing */\n privateKey: string;\n /** Number of documents to retrieve */\n k?: number;\n /** Filter by context */\n context?: string;\n /** API URL (defaults to https://api.xache.xyz) */\n apiUrl?: string;\n /** Chain: 'base' or 'solana' */\n chain?: 'base' | 'solana';\n}\n\n/**\n * Retriever that fetches documents from Xache memory storage.\n *\n * Use this for RAG pipelines with persistent, verifiable document storage.\n *\n * @example\n * ```typescript\n * import { XacheRetriever } from '@xache/langchain';\n * import { ChatOpenAI } from '@langchain/openai';\n * import { RetrievalQAChain } from 'langchain/chains';\n *\n * const retriever = new XacheRetriever({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * k: 5,\n * });\n *\n * const qa = RetrievalQAChain.fromLLM(new ChatOpenAI(), retriever);\n * const result = await qa.call({ query: 'What do you know about X?' });\n * ```\n */\nexport class XacheRetriever extends BaseRetriever {\n lc_namespace = ['xache', 'retriever'];\n\n static lc_name() {\n return 'XacheRetriever';\n }\n\n private client: XacheClient;\n private k: number;\n private filterContext?: string;\n\n constructor(config: XacheRetrieverConfig) {\n super(config);\n\n const chainPrefix = config.chain === 'solana' ? 'sol' : 'evm';\n const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}` as DID;\n\n this.client = new XacheClient({\n apiUrl: config.apiUrl || 'https://api.xache.xyz',\n did,\n privateKey: config.privateKey,\n });\n\n this.k = config.k ?? 5;\n this.filterContext = config.context;\n }\n\n async _getRelevantDocuments(\n _query: string,\n _runManager?: CallbackManagerForRetrieverRun\n ): Promise<Document[]> {\n // Use list method to get memories filtered by context\n const result = await this.client.memory.list({\n context: this.filterContext,\n limit: this.k,\n });\n\n const memories = result.memories || [];\n\n return memories.map(\n (m) =>\n new Document({\n pageContent: m.context || '',\n metadata: {\n storageKey: m.storage_key,\n context: m.context,\n tier: m.storage_tier,\n createdAt: m.created_at,\n size: m.size_bytes,\n },\n })\n );\n }\n}\n","/**\n * Xache Memory Extraction for LangChain.js\n * Auto-extract memories from conversations\n */\n\nimport { XacheClient, DID } from '@xache/sdk';\nimport type { ExtractMemoriesResponse, LLMProvider, LLMApiFormat } from '@xache/sdk';\n\nexport interface ExtractedMemory {\n /** Memory content */\n content: string;\n /** Suggested context/category */\n context: string;\n /** Suggested tags */\n tags: string[];\n /** Confidence score */\n confidence: number;\n /** Memory ID if stored */\n memoryId?: string;\n}\n\nexport interface ExtractionResult {\n /** Extracted memories */\n memories: ExtractedMemory[];\n /** Number of memories extracted */\n count: number;\n /** Total cost in USD */\n cost: number;\n /** Receipt ID for the operation */\n receiptId?: string;\n}\n\nexport interface XacheExtractorConfig {\n /** Wallet address for authentication */\n walletAddress: string;\n /** Private key for signing */\n privateKey: string;\n /**\n * Extraction mode:\n * - 'xache-managed': Xache provides the LLM ($0.011)\n * - 'api-key': Use major provider with known endpoint ($0.002)\n * - 'endpoint': Use custom/self-hosted endpoint ($0.002)\n */\n mode?: 'xache-managed' | 'api-key' | 'endpoint';\n /** Your LLM API key (required if mode is 'api-key') */\n llmApiKey?: string;\n /**\n * LLM provider for api-key mode\n * Supports: anthropic, openai, google, mistral, groq, together, fireworks, cohere, xai, deepseek\n */\n llmProvider?: LLMProvider;\n /** Custom endpoint URL (required if mode is 'endpoint') */\n endpointUrl?: string;\n /** Auth token for custom endpoint */\n endpointAuthToken?: string;\n /** API format for custom endpoint (default: 'openai') */\n endpointFormat?: LLMApiFormat;\n /** Model name (optional, uses provider/endpoint default) */\n model?: string;\n /** API URL (defaults to https://api.xache.xyz) */\n apiUrl?: string;\n /** Chain: 'base' or 'solana' */\n chain?: 'base' | 'solana';\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Enable debug logging */\n debug?: boolean;\n}\n\n/**\n * Extract memories from conversation traces.\n *\n * Can auto-store extracted memories to Xache for later retrieval.\n *\n * @example\n * ```typescript\n * import { XacheExtractor } from '@xache/langchain';\n *\n * const extractor = new XacheExtractor({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * mode: 'xache-managed',\n * });\n *\n * const result = await extractor.extract(\n * 'User: What is the capital of France?\\nAI: Paris is the capital.',\n * { autoStore: true }\n * );\n *\n * console.log(`Extracted ${result.count} memories`);\n * ```\n */\nexport class XacheExtractor {\n private client: XacheClient;\n private mode: 'xache-managed' | 'api-key' | 'endpoint';\n private llmApiKey?: string;\n private llmProvider: LLMProvider;\n private endpointUrl?: string;\n private endpointAuthToken?: string;\n private endpointFormat: LLMApiFormat;\n private model?: string;\n\n constructor(config: XacheExtractorConfig) {\n const mode = config.mode || 'xache-managed';\n\n // Validate api-key mode requires llmApiKey\n if (mode === 'api-key' && !config.llmApiKey) {\n throw new Error('llmApiKey is required when mode is \"api-key\"');\n }\n\n // Validate endpoint mode requires endpointUrl\n if (mode === 'endpoint' && !config.endpointUrl) {\n throw new Error('endpointUrl is required when mode is \"endpoint\"');\n }\n\n const chainPrefix = config.chain === 'solana' ? 'sol' : 'evm';\n const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}` as DID;\n\n this.client = new XacheClient({\n apiUrl: config.apiUrl || 'https://api.xache.xyz',\n did,\n privateKey: config.privateKey,\n timeout: config.timeout,\n debug: config.debug,\n });\n\n this.mode = mode;\n this.llmApiKey = config.llmApiKey;\n this.llmProvider = config.llmProvider || 'anthropic';\n this.endpointUrl = config.endpointUrl;\n this.endpointAuthToken = config.endpointAuthToken;\n this.endpointFormat = config.endpointFormat || 'openai';\n this.model = config.model;\n }\n\n /**\n * Extract memories from a conversation trace\n */\n async extract(\n trace: string,\n options?: {\n /** Automatically store extracted memories */\n autoStore?: boolean;\n /** Custom instructions for extraction */\n instructions?: string;\n /** Minimum confidence threshold (0-1) */\n minConfidence?: number;\n }\n ): Promise<ExtractionResult> {\n // Build llmConfig based on mode\n let llmConfig;\n if (this.mode === 'xache-managed') {\n llmConfig = {\n type: 'xache-managed' as const,\n provider: 'anthropic' as const,\n model: this.model,\n };\n } else if (this.mode === 'endpoint') {\n llmConfig = {\n type: 'endpoint' as const,\n url: this.endpointUrl!,\n authToken: this.endpointAuthToken,\n format: this.endpointFormat,\n model: this.model,\n };\n } else {\n llmConfig = {\n type: 'api-key' as const,\n provider: this.llmProvider,\n apiKey: this.llmApiKey || '',\n model: this.model,\n };\n }\n\n const result: ExtractMemoriesResponse = await this.client.extraction.extract({\n trace,\n llmConfig,\n options: {\n autoStore: options?.autoStore,\n contextHint: options?.instructions,\n },\n });\n\n const minConfidence = options?.minConfidence ?? 0;\n const memories: ExtractedMemory[] = (result.extractions || [])\n .filter((m) => (m.confidence || 1) >= minConfidence)\n .map((m, index) => ({\n content: m.reasoning || JSON.stringify(m.data) || '',\n context: m.type || 'extracted',\n tags: Object.keys(m.data || {}),\n confidence: m.confidence || 1,\n memoryId: result.stored?.[index],\n }));\n\n return {\n memories,\n count: memories.length,\n cost: 0, // Cost is handled by x402\n receiptId: result.metadata?.paymentReceiptId,\n };\n }\n\n /**\n * Extract from LangChain messages\n */\n async extractFromMessages(\n messages: Array<{ role: string; content: string }>,\n options?: {\n autoStore?: boolean;\n instructions?: string;\n minConfidence?: number;\n }\n ): Promise<ExtractionResult> {\n const trace = messages.map((m) => `${m.role}: ${m.content}`).join('\\n');\n\n return this.extract(trace, options);\n }\n}\n","/**\n * Xache Collective Intelligence for LangChain.js\n * Share and learn from collective knowledge pools\n */\n\nimport { DynamicStructuredTool } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport { XacheClient, DID } from '@xache/sdk';\n\n/**\n * Generate a hash for the pattern (simple implementation)\n */\nasync function generatePatternHash(pattern: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(pattern);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n}\n\nexport interface CollectiveToolConfig {\n /** Wallet address for authentication */\n walletAddress: string;\n /** Private key for signing */\n privateKey: string;\n /** API URL (defaults to https://api.xache.xyz) */\n apiUrl?: string;\n /** Chain: 'base' or 'solana' */\n chain?: 'base' | 'solana';\n}\n\n/**\n * Create an Xache client for collective tools\n */\nfunction createClient(config: CollectiveToolConfig): XacheClient {\n const chainPrefix = config.chain === 'solana' ? 'sol' : 'evm';\n const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}` as DID;\n\n return new XacheClient({\n apiUrl: config.apiUrl || 'https://api.xache.xyz',\n did,\n privateKey: config.privateKey,\n });\n}\n\n/**\n * Create a tool for contributing to collective intelligence.\n *\n * @example\n * ```typescript\n * import { createCollectiveContributeTool } from '@xache/langchain';\n *\n * const contributeTool = createCollectiveContributeTool({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * });\n *\n * const tools = [contributeTool, ...];\n * ```\n */\nexport function createCollectiveContributeTool(\n config: CollectiveToolConfig\n): DynamicStructuredTool {\n const client = createClient(config);\n\n return new DynamicStructuredTool({\n name: 'xache_collective_contribute',\n description:\n 'Contribute an insight or learning to the collective intelligence pool. ' +\n 'Use this when you discover something valuable that could help other agents. ' +\n \"You'll earn reputation for quality contributions.\",\n schema: z.object({\n insight: z.string().describe('The insight or learning to contribute'),\n domain: z.string().describe('Domain/topic of the insight'),\n evidence: z.string().optional().describe('Supporting evidence'),\n tags: z.array(z.string()).optional().describe('Tags for categorization'),\n }),\n func: async ({ insight, domain, evidence, tags }) => {\n // Generate required fields for the SDK\n const pattern = insight;\n const patternHash = await generatePatternHash(pattern);\n const tagsArray = tags || ['general'];\n\n const result = await client.collective.contribute({\n domain,\n pattern,\n patternHash,\n tags: tagsArray,\n metrics: {\n successRate: 0.8, // Default metrics for new contributions\n sampleSize: 1,\n confidence: 0.7,\n },\n encryptedContentRef: evidence || '', // Store evidence as encrypted ref\n });\n\n const heuristicId = result.heuristicId || 'unknown';\n const receiptId = result.receiptId || 'unknown';\n\n return `Contributed insight to '${domain}'. Heuristic ID: ${heuristicId}, Receipt: ${receiptId}`;\n },\n });\n}\n\n/**\n * Create a tool for querying collective intelligence.\n *\n * @example\n * ```typescript\n * import { createCollectiveQueryTool } from '@xache/langchain';\n *\n * const queryTool = createCollectiveQueryTool({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * });\n *\n * const tools = [queryTool, ...];\n * ```\n */\nexport function createCollectiveQueryTool(\n config: CollectiveToolConfig\n): DynamicStructuredTool {\n const client = createClient(config);\n\n return new DynamicStructuredTool({\n name: 'xache_collective_query',\n description:\n 'Query the collective intelligence pool to learn from other agents. ' +\n 'Use this when you need insights or knowledge from the community. ' +\n 'Returns relevant contributions from other agents.',\n schema: z.object({\n query: z.string().describe('What to search for in the collective'),\n domain: z.string().optional().describe('Filter by domain'),\n limit: z.number().optional().default(5).describe('Number of results'),\n }),\n func: async ({ query, domain, limit }) => {\n const result = await client.collective.query({\n queryText: query,\n domain,\n limit: limit || 5,\n });\n\n const results = result.matches || [];\n\n if (results.length === 0) {\n return 'No relevant insights found in the collective.';\n }\n\n let output = `Found ${results.length} insights:\\n`;\n\n results.forEach((item, i: number) => {\n const pattern = (item.pattern || '').slice(0, 200);\n output += `\\n${i + 1}. ${pattern}`;\n if (item.domain) {\n output += ` [Domain: ${item.domain}]`;\n }\n if (item.relevanceScore) {\n output += ` (Relevance: ${item.relevanceScore.toFixed(2)})`;\n }\n });\n\n return output;\n },\n });\n}\n\n/**\n * Class-based collective contribute tool (alternative API)\n */\nexport class XacheCollectiveContributeTool {\n private tool: DynamicStructuredTool;\n\n constructor(config: CollectiveToolConfig) {\n this.tool = createCollectiveContributeTool(config);\n }\n\n asTool(): DynamicStructuredTool {\n return this.tool;\n }\n}\n\n/**\n * Class-based collective query tool (alternative API)\n */\nexport class XacheCollectiveQueryTool {\n private tool: DynamicStructuredTool;\n\n constructor(config: CollectiveToolConfig) {\n this.tool = createCollectiveQueryTool(config);\n }\n\n asTool(): DynamicStructuredTool {\n return this.tool;\n }\n}\n","/**\n * Xache Reputation for LangChain.js\n * Portable, verifiable agent reputation with ERC-8004 support\n */\n\nimport { DynamicStructuredTool } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport { XacheClient, DID } from '@xache/sdk';\n\nexport interface ReputationToolConfig {\n /** Wallet address for authentication */\n walletAddress: string;\n /** Private key for signing */\n privateKey: string;\n /** API URL (defaults to https://api.xache.xyz) */\n apiUrl?: string;\n /** Chain: 'base' or 'solana' */\n chain?: 'base' | 'solana';\n}\n\nexport interface ReputationResult {\n /** Reputation score (0-1) */\n score: number;\n /** Reputation level */\n level: string;\n /** Total contributions made */\n totalContributions: number;\n /** Total payments made */\n totalPayments: number;\n /** Whether ERC-8004 is enabled */\n erc8004Enabled: boolean;\n /** ERC-8004 agent ID if enabled */\n erc8004AgentId?: string;\n}\n\n/**\n * Get reputation level from score\n */\nfunction getLevel(score: number): string {\n if (score >= 0.9) return 'Elite';\n if (score >= 0.7) return 'Trusted';\n if (score >= 0.5) return 'Established';\n if (score >= 0.3) return 'Developing';\n return 'New';\n}\n\n/**\n * Create an Xache client for reputation tools\n */\nfunction createClient(config: ReputationToolConfig): XacheClient {\n const chainPrefix = config.chain === 'solana' ? 'sol' : 'evm';\n const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}` as DID;\n\n return new XacheClient({\n apiUrl: config.apiUrl || 'https://api.xache.xyz',\n did,\n privateKey: config.privateKey,\n });\n}\n\n/**\n * Create a tool for checking your own reputation.\n *\n * @example\n * ```typescript\n * import { createReputationTool } from '@xache/langchain';\n *\n * const repTool = createReputationTool({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * });\n *\n * const tools = [repTool, ...];\n * ```\n */\nexport function createReputationTool(\n config: ReputationToolConfig\n): DynamicStructuredTool {\n const client = createClient(config);\n\n return new DynamicStructuredTool({\n name: 'xache_check_reputation',\n description:\n 'Check your current reputation score and status. ' +\n 'Returns your score (0-1), level, and ERC-8004 on-chain status. ' +\n 'Higher reputation means lower costs and more trust from other agents.',\n schema: z.object({}),\n func: async () => {\n const result = await client.reputation.getReputation();\n\n // Overall score is 0-100, normalize to 0-1\n const score = (result.overall || 0) / 100;\n const level = getLevel(score);\n\n let output = `Reputation Score: ${score.toFixed(2)}/1.00 (${level})\\n`;\n output += `Memory Quality: ${result.memoryQuality || 0}/100\\n`;\n output += `Contribution Success: ${result.contribSuccess || 0}/100\\n`;\n output += `Economic Value: ${result.economicValue || 0}/100\\n`;\n\n // Check ERC-8004 status separately\n try {\n const erc8004Status = await client.reputation.getERC8004Status();\n if (erc8004Status.enabled) {\n output += `ERC-8004 Status: Enabled\\n`;\n output += 'Your reputation is verifiable on-chain!';\n } else {\n output += 'ERC-8004 Status: Not enabled\\n';\n output += 'Enable ERC-8004 to make your reputation portable and verifiable.';\n }\n } catch {\n output += 'ERC-8004 Status: Unknown';\n }\n\n return output;\n },\n });\n}\n\n/**\n * Class-based reputation tool (alternative API)\n */\nexport class XacheReputationTool {\n private tool: DynamicStructuredTool;\n\n constructor(config: ReputationToolConfig) {\n this.tool = createReputationTool(config);\n }\n\n asTool(): DynamicStructuredTool {\n return this.tool;\n }\n}\n\n/**\n * Utility class for checking reputation of any agent.\n *\n * @example\n * ```typescript\n * import { XacheReputationChecker } from '@xache/langchain';\n *\n * const checker = new XacheReputationChecker({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * });\n *\n * const rep = await checker.check('did:agent:evm:0xOtherAgent...');\n * if (rep.score >= 0.5) {\n * console.log('Agent is trustworthy');\n * }\n * ```\n */\nexport class XacheReputationChecker {\n private client: XacheClient;\n\n constructor(config: ReputationToolConfig) {\n this.client = createClient(config);\n }\n\n /**\n * Check an agent's reputation\n */\n async check(agentDid: string): Promise<ReputationResult> {\n const result = await this.client.reputation.getReputation(agentDid as DID);\n\n // Overall score is 0-100, normalize to 0-1\n const score = (result.overall || 0) / 100;\n\n // Try to get ERC-8004 status\n let erc8004Enabled = false;\n let erc8004AgentId: string | undefined;\n try {\n const erc8004Status = await this.client.reputation.getERC8004Status();\n erc8004Enabled = erc8004Status.enabled;\n } catch {\n // ERC-8004 status not available\n }\n\n return {\n score,\n level: getLevel(score),\n totalContributions: 0, // Not available in current API\n totalPayments: 0, // Not available in current API\n erc8004Enabled,\n erc8004AgentId,\n };\n }\n\n /**\n * Check if an agent meets minimum reputation threshold\n */\n async meetsThreshold(agentDid: string, minScore: number): Promise<boolean> {\n const result = await this.check(agentDid);\n return result.score >= minScore;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,oBAAuE;;;ACAvE,0BAA2C;AAC3C,sBAKO;AACP,iBAAiC;AACjC,oBAA2B;AA6CpB,IAAM,0BAAN,cAAsC,+CAA2B;AAAA,EAUtE,YAAY,QAAuC;AACjD,UAAM;AAVR,wBAAe,CAAC,SAAS,cAAc;AAIvC,SAAQ,WAA0B,CAAC;AACnC,SAAQ,cAAc;AAOpB,UAAM,cAAc,OAAO,UAAU,WAAW,QAAQ;AACxD,UAAM,MAAM,aAAa,WAAW,IAAI,OAAO,cAAc,YAAY,CAAC;AAE1E,SAAK,SAAS,IAAI,uBAAY;AAAA,MAC5B,QAAQ,OAAO,UAAU;AAAA,MACzB;AAAA,MACA,YAAY,OAAO;AAAA,MACnB,SAAS,OAAO;AAAA,MAChB,OAAO,OAAO;AAAA,IAChB,CAAC;AAGD,SAAK,YAAY,OAAO,aAAa,iBAAa,0BAAW,CAAC;AAC9D,SAAK,cAAc,OAAO,eAAe;AACzC,SAAK,WAAW,OAAO,YAAY;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,cAAsC;AAC1C,QAAI,CAAC,KAAK,aAAa;AACrB,YAAM,KAAK,aAAa;AAAA,IAC1B;AACA,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,WAAW,SAAqC;AACpD,SAAK,SAAS,KAAK,OAAO;AAE1B,UAAM,OAAO,KAAK,eAAe,OAAO;AACxC,UAAM,UACJ,OAAO,QAAQ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AO,qBAAqB,MAAM;AAAA,EACzC;AAAA,EAEA,SAAgC;AAC9B,WAAO,KAAK;AAAA,EACd;AACF;AAoBO,IAAM,yBAAN,MAA6B;AAAA,EAGlC,YAAY,QAA8B;AACxC,SAAK,SAASA,cAAa,MAAM;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,MAAM,UAA6C;AACvD,UAAM,SAAS,MAAM,KAAK,OAAO,WAAW,cAAc,QAAe;AAGzE,UAAM,SAAS,OAAO,WAAW,KAAK;AAGtC,QAAI,iBAAiB;AACrB,QAAI;AACJ,QAAI;AACF,YAAM,gBAAgB,MAAM,KAAK,OAAO,WAAW,iBAAiB;AACpE,uBAAiB,cAAc;AAAA,IACjC,QAAQ;AAAA,IAER;AAEA,WAAO;AAAA,MACL;AAAA,MACA,OAAO,SAAS,KAAK;AAAA,MACrB,oBAAoB;AAAA;AAAA,MACpB,eAAe;AAAA;AAAA,MACf;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,eAAe,UAAkB,UAAoC;AACzE,UAAM,SAAS,MAAM,KAAK,MAAM,QAAQ;AACxC,WAAO,OAAO,SAAS;AAAA,EACzB;AACF;","names":["import_sdk","import_sdk","import_sdk","import_tools","import_zod","import_sdk","createClient"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/memory.ts","../src/chat_history.ts","../src/retriever.ts","../src/extraction.ts","../src/collective.ts","../src/reputation.ts","../src/graph.ts"],"sourcesContent":["/**\n * @xache/langchain\n * LangChain.js integration for Xache Protocol\n *\n * Drop-in memory, retrieval, and collective intelligence with verifiable receipts.\n *\n * @example\n * ```typescript\n * // One-line memory replacement\n * import { XacheMemory } from '@xache/langchain';\n *\n * const memory = new XacheMemory({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * });\n *\n * // Use with any LangChain chain\n * const chain = new ConversationChain({ llm, memory });\n * ```\n *\n * @packageDocumentation\n */\n\n// Memory\nexport { XacheMemory, XacheConversationBufferMemory } from './memory';\nexport type { XacheMemoryConfig } from './memory';\n\n// Chat History\nexport { XacheChatMessageHistory } from './chat_history';\nexport type { XacheChatMessageHistoryConfig } from './chat_history';\n\n// Retrieval\nexport { XacheRetriever } from './retriever';\nexport type { XacheRetrieverConfig } from './retriever';\n\n// Extraction\nexport { XacheExtractor } from './extraction';\nexport type {\n XacheExtractorConfig,\n ExtractedMemory,\n ExtractionResult,\n} from './extraction';\n\n// Collective Intelligence\nexport {\n createCollectiveContributeTool,\n createCollectiveQueryTool,\n XacheCollectiveContributeTool,\n XacheCollectiveQueryTool,\n} from './collective';\nexport type { CollectiveToolConfig } from './collective';\n\n// Reputation\nexport {\n createReputationTool,\n XacheReputationTool,\n XacheReputationChecker,\n} from './reputation';\nexport type { ReputationToolConfig, ReputationResult } from './reputation';\n\n// Knowledge Graph\nexport {\n createGraphExtractTool,\n createGraphLoadTool,\n createGraphQueryTool,\n createGraphAskTool,\n createGraphAddEntityTool,\n createGraphAddRelationshipTool,\n createGraphMergeEntitiesTool,\n createGraphEntityHistoryTool,\n XacheGraphExtractTool,\n XacheGraphLoadTool,\n XacheGraphQueryTool,\n XacheGraphAskTool,\n XacheGraphMergeEntitiesTool,\n XacheGraphEntityHistoryTool,\n XacheGraphRetriever,\n} from './graph';\nexport type { GraphToolConfig, XacheGraphRetrieverConfig } from './graph';\n","/**\n * Xache Memory for LangChain.js\n * Drop-in replacement for ConversationBufferMemory with verifiable receipts\n */\n\nimport { BaseMemory, InputValues, OutputValues, MemoryVariables } from '@langchain/core/memory';\nimport { XacheChatMessageHistory, XacheChatMessageHistoryConfig } from './chat_history';\n\nexport interface XacheMemoryConfig extends XacheChatMessageHistoryConfig {\n /** Memory key for input (default: 'input') */\n inputKey?: string;\n /** Memory key for output (default: 'output') */\n outputKey?: string;\n /** Key for returning memory (default: 'history') */\n memoryKey?: string;\n /** Return messages as list vs string */\n returnMessages?: boolean;\n}\n\n/**\n * Drop-in replacement for LangChain memory with Xache storage.\n *\n * Provides persistent, verifiable memory that survives across sessions.\n *\n * @example\n * ```typescript\n * import { XacheMemory } from '@xache/langchain';\n * import { ChatOpenAI } from '@langchain/openai';\n * import { ConversationChain } from 'langchain/chains';\n *\n * const memory = new XacheMemory({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * });\n *\n * const chain = new ConversationChain({\n * llm: new ChatOpenAI(),\n * memory,\n * });\n *\n * await chain.call({ input: 'Hello!' });\n * ```\n */\nexport class XacheMemory extends BaseMemory {\n lc_namespace = ['xache', 'memory'];\n\n private chatHistory: XacheChatMessageHistory;\n private inputKey: string;\n private outputKey: string;\n private memoryKey: string;\n private returnMessages: boolean;\n\n constructor(config: XacheMemoryConfig) {\n super();\n this.chatHistory = new XacheChatMessageHistory(config);\n this.inputKey = config.inputKey || 'input';\n this.outputKey = config.outputKey || 'output';\n this.memoryKey = config.memoryKey || 'history';\n this.returnMessages = config.returnMessages ?? false;\n }\n\n get memoryKeys(): string[] {\n return [this.memoryKey];\n }\n\n /**\n * Load memory variables\n */\n async loadMemoryVariables(_values: InputValues): Promise<MemoryVariables> {\n const messages = await this.chatHistory.getMessages();\n\n if (this.returnMessages) {\n return { [this.memoryKey]: messages };\n }\n\n // Convert to string format\n const history = messages\n .map((m) => {\n const role = m._getType() === 'human' ? 'Human' : 'AI';\n const content =\n typeof m.content === 'string' ? m.content : JSON.stringify(m.content);\n return `${role}: ${content}`;\n })\n .join('\\n');\n\n return { [this.memoryKey]: history };\n }\n\n /**\n * Save context from this conversation to buffer\n */\n async saveContext(\n inputValues: InputValues,\n outputValues: OutputValues\n ): Promise<void> {\n const input = inputValues[this.inputKey];\n const output = outputValues[this.outputKey];\n\n if (input) {\n await this.chatHistory.addUserMessage(String(input));\n }\n\n if (output) {\n await this.chatHistory.addAIMessage(String(output));\n }\n }\n\n /**\n * Clear memory contents\n */\n async clear(): Promise<void> {\n await this.chatHistory.clear();\n }\n}\n\n/**\n * Extended memory with conversation buffer capabilities\n */\nexport class XacheConversationBufferMemory extends XacheMemory {\n lc_namespace = ['xache', 'memory', 'buffer'];\n}\n","/**\n * Xache Chat Message History for LangChain.js\n * Persistent message storage with cryptographic receipts\n */\n\nimport { BaseListChatMessageHistory } from '@langchain/core/chat_history';\nimport {\n BaseMessage,\n HumanMessage,\n AIMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport { XacheClient, DID } from '@xache/sdk';\nimport { randomUUID } from 'crypto';\n\nexport interface XacheChatMessageHistoryConfig {\n /** Wallet address for authentication */\n walletAddress: string;\n /** Private key for signing */\n privateKey: string;\n /** Session ID to group messages */\n sessionId?: string;\n /** API URL (defaults to https://api.xache.xyz) */\n apiUrl?: string;\n /** Chain: 'base' or 'solana' */\n chain?: 'base' | 'solana';\n /** Maximum messages to load (default: 1000, set to -1 for unlimited) */\n maxMessages?: number;\n /** Page size for loading messages (default: 100) */\n pageSize?: number;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Enable debug logging */\n debug?: boolean;\n}\n\n/**\n * Chat message history backed by Xache Protocol.\n *\n * Messages are stored with cryptographic receipts and can persist\n * across sessions.\n *\n * @example\n * ```typescript\n * import { XacheChatMessageHistory } from '@xache/langchain';\n *\n * const history = new XacheChatMessageHistory({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * sessionId: 'unique-session-id',\n * });\n *\n * await history.addUserMessage('Hello!');\n * await history.addAIMessage('Hi there!');\n *\n * const messages = await history.getMessages();\n * ```\n */\nexport class XacheChatMessageHistory extends BaseListChatMessageHistory {\n lc_namespace = ['xache', 'chat_history'];\n\n private client: XacheClient;\n private sessionId: string;\n private messages: BaseMessage[] = [];\n private initialized = false;\n private maxMessages: number;\n private pageSize: number;\n\n constructor(config: XacheChatMessageHistoryConfig) {\n super();\n\n const chainPrefix = config.chain === 'solana' ? 'sol' : 'evm';\n const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}` as DID;\n\n this.client = new XacheClient({\n apiUrl: config.apiUrl || 'https://api.xache.xyz',\n did,\n privateKey: config.privateKey,\n timeout: config.timeout,\n debug: config.debug,\n });\n\n // Use UUID for collision-resistant session IDs\n this.sessionId = config.sessionId || `langchain-${randomUUID()}`;\n this.maxMessages = config.maxMessages ?? 1000;\n this.pageSize = config.pageSize ?? 100;\n }\n\n /**\n * Get all messages in the history\n */\n async getMessages(): Promise<BaseMessage[]> {\n if (!this.initialized) {\n await this.loadMessages();\n }\n return this.messages;\n }\n\n /**\n * Add a message to the history\n */\n async addMessage(message: BaseMessage): Promise<void> {\n this.messages.push(message);\n\n const role = this.getMessageRole(message);\n const content =\n typeof message.content === 'string'\n ? message.content\n : JSON.stringify(message.content);\n\n await this.client.memory.store({\n data: {\n role,\n content,\n sessionId: this.sessionId,\n timestamp: Date.now(),\n },\n storageTier: 'hot',\n context: `chat:${this.sessionId}`,\n tags: ['chat', 'message', role],\n metadata: {\n sessionId: this.sessionId,\n role,\n },\n });\n }\n\n /**\n * Add a user message\n */\n async addUserMessage(message: string): Promise<void> {\n await this.addMessage(new HumanMessage(message));\n }\n\n /**\n * Add an AI message\n */\n async addAIMessage(message: string): Promise<void> {\n await this.addMessage(new AIMessage(message));\n }\n\n /**\n * Clear all messages from history\n */\n async clear(): Promise<void> {\n this.messages = [];\n // Note: Xache doesn't support deletion - messages remain for audit trail\n // We only clear the local cache\n }\n\n /**\n * Load messages from Xache storage with pagination support\n */\n private async loadMessages(): Promise<void> {\n try {\n const allMemories: Array<{ storage_key: string; created_at?: string }> = [];\n let offset = 0;\n const effectiveMax = this.maxMessages === -1 ? Infinity : this.maxMessages;\n\n // Paginate through all messages\n while (allMemories.length < effectiveMax) {\n const result = await this.client.memory.list({\n context: `chat:${this.sessionId}`,\n limit: Math.min(this.pageSize, effectiveMax - allMemories.length),\n offset,\n });\n\n const memories = Array.isArray(result?.memories) ? result.memories : [];\n if (memories.length === 0) break;\n\n allMemories.push(...memories);\n offset += memories.length;\n\n // If we got less than pageSize, we've reached the end\n if (memories.length < this.pageSize) break;\n }\n\n // Sort by timestamp\n const sortedMemories = [...allMemories].sort((a, b) => {\n const tsA = new Date(a.created_at || 0).getTime();\n const tsB = new Date(b.created_at || 0).getTime();\n return tsA - tsB;\n });\n\n // For each memory, we need to retrieve the full content\n this.messages = [];\n for (const m of sortedMemories) {\n try {\n const full = await this.client.memory.retrieve({\n storageKey: m.storage_key,\n });\n const data = full.data as { role?: string; content?: string };\n if (data && data.content) {\n switch (data.role) {\n case 'human':\n case 'user':\n this.messages.push(new HumanMessage(data.content));\n break;\n case 'ai':\n case 'assistant':\n this.messages.push(new AIMessage(data.content));\n break;\n case 'system':\n this.messages.push(new SystemMessage(data.content));\n break;\n default:\n this.messages.push(new HumanMessage(data.content));\n }\n }\n } catch (error) {\n // Skip malformed messages but log in debug\n console.debug?.(`[XacheChatMessageHistory] Failed to parse message: ${(error as Error).message}`);\n }\n }\n\n this.initialized = true;\n } catch (error) {\n // If retrieval fails (e.g., no memories yet), start fresh\n // This is expected for new sessions\n console.debug?.(`[XacheChatMessageHistory] No existing messages found: ${(error as Error).message}`);\n this.messages = [];\n this.initialized = true;\n }\n }\n\n private getMessageRole(message: BaseMessage): string {\n if (message instanceof HumanMessage) return 'human';\n if (message instanceof AIMessage) return 'ai';\n if (message instanceof SystemMessage) return 'system';\n return 'unknown';\n }\n}\n","/**\n * Xache Retriever for LangChain.js\n * Memory retrieval for RAG pipelines with verifiable receipts\n */\n\nimport { BaseRetriever, BaseRetrieverInput } from '@langchain/core/retrievers';\nimport { Document } from '@langchain/core/documents';\nimport { CallbackManagerForRetrieverRun } from '@langchain/core/callbacks/manager';\nimport { XacheClient, DID } from '@xache/sdk';\n\nexport interface XacheRetrieverConfig extends BaseRetrieverInput {\n /** Wallet address for authentication */\n walletAddress: string;\n /** Private key for signing */\n privateKey: string;\n /** Number of documents to retrieve */\n k?: number;\n /** Filter by context */\n context?: string;\n /** API URL (defaults to https://api.xache.xyz) */\n apiUrl?: string;\n /** Chain: 'base' or 'solana' */\n chain?: 'base' | 'solana';\n}\n\n/**\n * Retriever that fetches documents from Xache memory storage.\n *\n * Use this for RAG pipelines with persistent, verifiable document storage.\n *\n * @example\n * ```typescript\n * import { XacheRetriever } from '@xache/langchain';\n * import { ChatOpenAI } from '@langchain/openai';\n * import { RetrievalQAChain } from 'langchain/chains';\n *\n * const retriever = new XacheRetriever({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * k: 5,\n * });\n *\n * const qa = RetrievalQAChain.fromLLM(new ChatOpenAI(), retriever);\n * const result = await qa.call({ query: 'What do you know about X?' });\n * ```\n */\nexport class XacheRetriever extends BaseRetriever {\n lc_namespace = ['xache', 'retriever'];\n\n static lc_name() {\n return 'XacheRetriever';\n }\n\n private client: XacheClient;\n private k: number;\n private filterContext?: string;\n\n constructor(config: XacheRetrieverConfig) {\n super(config);\n\n const chainPrefix = config.chain === 'solana' ? 'sol' : 'evm';\n const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}` as DID;\n\n this.client = new XacheClient({\n apiUrl: config.apiUrl || 'https://api.xache.xyz',\n did,\n privateKey: config.privateKey,\n });\n\n this.k = config.k ?? 5;\n this.filterContext = config.context;\n }\n\n async _getRelevantDocuments(\n _query: string,\n _runManager?: CallbackManagerForRetrieverRun\n ): Promise<Document[]> {\n // Use list method to get memories filtered by context\n const result = await this.client.memory.list({\n context: this.filterContext,\n limit: this.k,\n });\n\n const memories = result.memories || [];\n\n return memories.map(\n (m) =>\n new Document({\n pageContent: m.context || '',\n metadata: {\n storageKey: m.storage_key,\n context: m.context,\n tier: m.storage_tier,\n createdAt: m.created_at,\n size: m.size_bytes,\n },\n })\n );\n }\n}\n","/**\n * Xache Memory Extraction for LangChain.js\n * Auto-extract memories from conversations\n */\n\nimport { XacheClient, DID } from '@xache/sdk';\nimport type { ExtractMemoriesResponse, LLMProvider, LLMApiFormat } from '@xache/sdk';\n\nexport interface ExtractedMemory {\n /** Memory content */\n content: string;\n /** Suggested context/category */\n context: string;\n /** Suggested tags */\n tags: string[];\n /** Confidence score */\n confidence: number;\n /** Memory ID if stored */\n memoryId?: string;\n}\n\nexport interface ExtractionResult {\n /** Extracted memories */\n memories: ExtractedMemory[];\n /** Number of memories extracted */\n count: number;\n /** Total cost in USD */\n cost: number;\n /** Receipt ID for the operation */\n receiptId?: string;\n}\n\nexport interface XacheExtractorConfig {\n /** Wallet address for authentication */\n walletAddress: string;\n /** Private key for signing */\n privateKey: string;\n /**\n * Extraction mode:\n * - 'xache-managed': Xache provides the LLM ($0.011)\n * - 'api-key': Use major provider with known endpoint ($0.002)\n * - 'endpoint': Use custom/self-hosted endpoint ($0.002)\n */\n mode?: 'xache-managed' | 'api-key' | 'endpoint';\n /** Your LLM API key (required if mode is 'api-key') */\n llmApiKey?: string;\n /**\n * LLM provider for api-key mode\n * Supports: anthropic, openai, google, mistral, groq, together, fireworks, cohere, xai, deepseek\n */\n llmProvider?: LLMProvider;\n /** Custom endpoint URL (required if mode is 'endpoint') */\n endpointUrl?: string;\n /** Auth token for custom endpoint */\n endpointAuthToken?: string;\n /** API format for custom endpoint (default: 'openai') */\n endpointFormat?: LLMApiFormat;\n /** Model name (optional, uses provider/endpoint default) */\n model?: string;\n /** API URL (defaults to https://api.xache.xyz) */\n apiUrl?: string;\n /** Chain: 'base' or 'solana' */\n chain?: 'base' | 'solana';\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Enable debug logging */\n debug?: boolean;\n}\n\n/**\n * Extract memories from conversation traces.\n *\n * Can auto-store extracted memories to Xache for later retrieval.\n *\n * @example\n * ```typescript\n * import { XacheExtractor } from '@xache/langchain';\n *\n * const extractor = new XacheExtractor({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * mode: 'xache-managed',\n * });\n *\n * const result = await extractor.extract(\n * 'User: What is the capital of France?\\nAI: Paris is the capital.',\n * { autoStore: true }\n * );\n *\n * console.log(`Extracted ${result.count} memories`);\n * ```\n */\nexport class XacheExtractor {\n private client: XacheClient;\n private mode: 'xache-managed' | 'api-key' | 'endpoint';\n private llmApiKey?: string;\n private llmProvider: LLMProvider;\n private endpointUrl?: string;\n private endpointAuthToken?: string;\n private endpointFormat: LLMApiFormat;\n private model?: string;\n\n constructor(config: XacheExtractorConfig) {\n const mode = config.mode || 'xache-managed';\n\n // Validate api-key mode requires llmApiKey\n if (mode === 'api-key' && !config.llmApiKey) {\n throw new Error('llmApiKey is required when mode is \"api-key\"');\n }\n\n // Validate endpoint mode requires endpointUrl\n if (mode === 'endpoint' && !config.endpointUrl) {\n throw new Error('endpointUrl is required when mode is \"endpoint\"');\n }\n\n const chainPrefix = config.chain === 'solana' ? 'sol' : 'evm';\n const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}` as DID;\n\n this.client = new XacheClient({\n apiUrl: config.apiUrl || 'https://api.xache.xyz',\n did,\n privateKey: config.privateKey,\n timeout: config.timeout,\n debug: config.debug,\n });\n\n this.mode = mode;\n this.llmApiKey = config.llmApiKey;\n this.llmProvider = config.llmProvider || 'anthropic';\n this.endpointUrl = config.endpointUrl;\n this.endpointAuthToken = config.endpointAuthToken;\n this.endpointFormat = config.endpointFormat || 'openai';\n this.model = config.model;\n }\n\n /**\n * Extract memories from a conversation trace\n */\n async extract(\n trace: string,\n options?: {\n /** Automatically store extracted memories */\n autoStore?: boolean;\n /** Custom instructions for extraction */\n instructions?: string;\n /** Minimum confidence threshold (0-1) */\n minConfidence?: number;\n }\n ): Promise<ExtractionResult> {\n // Build llmConfig based on mode\n let llmConfig;\n if (this.mode === 'xache-managed') {\n llmConfig = {\n type: 'xache-managed' as const,\n provider: 'anthropic' as const,\n model: this.model,\n };\n } else if (this.mode === 'endpoint') {\n llmConfig = {\n type: 'endpoint' as const,\n url: this.endpointUrl!,\n authToken: this.endpointAuthToken,\n format: this.endpointFormat,\n model: this.model,\n };\n } else {\n llmConfig = {\n type: 'api-key' as const,\n provider: this.llmProvider,\n apiKey: this.llmApiKey || '',\n model: this.model,\n };\n }\n\n const result: ExtractMemoriesResponse = await this.client.extraction.extract({\n trace,\n llmConfig,\n options: {\n autoStore: options?.autoStore,\n contextHint: options?.instructions,\n },\n });\n\n const minConfidence = options?.minConfidence ?? 0;\n const memories: ExtractedMemory[] = (result.extractions || [])\n .filter((m) => (m.confidence || 1) >= minConfidence)\n .map((m, index) => ({\n content: m.reasoning || JSON.stringify(m.data) || '',\n context: m.type || 'extracted',\n tags: Object.keys(m.data || {}),\n confidence: m.confidence || 1,\n memoryId: result.stored?.[index],\n }));\n\n return {\n memories,\n count: memories.length,\n cost: 0, // Cost is handled by x402\n receiptId: result.metadata?.paymentReceiptId,\n };\n }\n\n /**\n * Extract from LangChain messages\n */\n async extractFromMessages(\n messages: Array<{ role: string; content: string }>,\n options?: {\n autoStore?: boolean;\n instructions?: string;\n minConfidence?: number;\n }\n ): Promise<ExtractionResult> {\n const trace = messages.map((m) => `${m.role}: ${m.content}`).join('\\n');\n\n return this.extract(trace, options);\n }\n}\n","/**\n * Xache Collective Intelligence for LangChain.js\n * Share and learn from collective knowledge pools\n */\n\nimport { DynamicStructuredTool } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport { XacheClient, DID } from '@xache/sdk';\n\n/**\n * Generate a hash for the pattern (simple implementation)\n */\nasync function generatePatternHash(pattern: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(pattern);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n}\n\nexport interface CollectiveToolConfig {\n /** Wallet address for authentication */\n walletAddress: string;\n /** Private key for signing */\n privateKey: string;\n /** API URL (defaults to https://api.xache.xyz) */\n apiUrl?: string;\n /** Chain: 'base' or 'solana' */\n chain?: 'base' | 'solana';\n}\n\n/**\n * Create an Xache client for collective tools\n */\nfunction createClient(config: CollectiveToolConfig): XacheClient {\n const chainPrefix = config.chain === 'solana' ? 'sol' : 'evm';\n const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}` as DID;\n\n return new XacheClient({\n apiUrl: config.apiUrl || 'https://api.xache.xyz',\n did,\n privateKey: config.privateKey,\n });\n}\n\n/**\n * Create a tool for contributing to collective intelligence.\n *\n * @example\n * ```typescript\n * import { createCollectiveContributeTool } from '@xache/langchain';\n *\n * const contributeTool = createCollectiveContributeTool({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * });\n *\n * const tools = [contributeTool, ...];\n * ```\n */\nexport function createCollectiveContributeTool(\n config: CollectiveToolConfig\n): DynamicStructuredTool {\n const client = createClient(config);\n\n return new DynamicStructuredTool({\n name: 'xache_collective_contribute',\n description:\n 'Contribute an insight or learning to the collective intelligence pool. ' +\n 'Use this when you discover something valuable that could help other agents. ' +\n \"You'll earn reputation for quality contributions.\",\n schema: z.object({\n insight: z.string().describe('The insight or learning to contribute'),\n domain: z.string().describe('Domain/topic of the insight'),\n evidence: z.string().optional().describe('Supporting evidence'),\n tags: z.array(z.string()).optional().describe('Tags for categorization'),\n }),\n func: async ({ insight, domain, evidence, tags }) => {\n // Generate required fields for the SDK\n const pattern = insight;\n const patternHash = await generatePatternHash(pattern);\n const tagsArray = tags || ['general'];\n\n const result = await client.collective.contribute({\n domain,\n pattern,\n patternHash,\n tags: tagsArray,\n metrics: {\n successRate: 0.8, // Default metrics for new contributions\n sampleSize: 1,\n confidence: 0.7,\n },\n encryptedContentRef: evidence || '', // Store evidence as encrypted ref\n });\n\n const heuristicId = result.heuristicId || 'unknown';\n const receiptId = result.receiptId || 'unknown';\n\n return `Contributed insight to '${domain}'. Heuristic ID: ${heuristicId}, Receipt: ${receiptId}`;\n },\n });\n}\n\n/**\n * Create a tool for querying collective intelligence.\n *\n * @example\n * ```typescript\n * import { createCollectiveQueryTool } from '@xache/langchain';\n *\n * const queryTool = createCollectiveQueryTool({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * });\n *\n * const tools = [queryTool, ...];\n * ```\n */\nexport function createCollectiveQueryTool(\n config: CollectiveToolConfig\n): DynamicStructuredTool {\n const client = createClient(config);\n\n return new DynamicStructuredTool({\n name: 'xache_collective_query',\n description:\n 'Query the collective intelligence pool to learn from other agents. ' +\n 'Use this when you need insights or knowledge from the community. ' +\n 'Returns relevant contributions from other agents.',\n schema: z.object({\n query: z.string().describe('What to search for in the collective'),\n domain: z.string().optional().describe('Filter by domain'),\n limit: z.number().optional().default(5).describe('Number of results'),\n }),\n func: async ({ query, domain, limit }) => {\n const result = await client.collective.query({\n queryText: query,\n domain,\n limit: limit || 5,\n });\n\n const results = result.matches || [];\n\n if (results.length === 0) {\n return 'No relevant insights found in the collective.';\n }\n\n let output = `Found ${results.length} insights:\\n`;\n\n results.forEach((item, i: number) => {\n const pattern = (item.pattern || '').slice(0, 200);\n output += `\\n${i + 1}. ${pattern}`;\n if (item.domain) {\n output += ` [Domain: ${item.domain}]`;\n }\n if (item.relevanceScore) {\n output += ` (Relevance: ${item.relevanceScore.toFixed(2)})`;\n }\n });\n\n return output;\n },\n });\n}\n\n/**\n * Class-based collective contribute tool (alternative API)\n */\nexport class XacheCollectiveContributeTool {\n private tool: DynamicStructuredTool;\n\n constructor(config: CollectiveToolConfig) {\n this.tool = createCollectiveContributeTool(config);\n }\n\n asTool(): DynamicStructuredTool {\n return this.tool;\n }\n}\n\n/**\n * Class-based collective query tool (alternative API)\n */\nexport class XacheCollectiveQueryTool {\n private tool: DynamicStructuredTool;\n\n constructor(config: CollectiveToolConfig) {\n this.tool = createCollectiveQueryTool(config);\n }\n\n asTool(): DynamicStructuredTool {\n return this.tool;\n }\n}\n","/**\n * Xache Reputation for LangChain.js\n * Portable, verifiable agent reputation with ERC-8004 support\n */\n\nimport { DynamicStructuredTool } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport { XacheClient, DID } from '@xache/sdk';\n\nexport interface ReputationToolConfig {\n /** Wallet address for authentication */\n walletAddress: string;\n /** Private key for signing */\n privateKey: string;\n /** API URL (defaults to https://api.xache.xyz) */\n apiUrl?: string;\n /** Chain: 'base' or 'solana' */\n chain?: 'base' | 'solana';\n}\n\nexport interface ReputationResult {\n /** Reputation score (0-1) */\n score: number;\n /** Reputation level */\n level: string;\n /** Total contributions made */\n totalContributions: number;\n /** Total payments made */\n totalPayments: number;\n /** Whether ERC-8004 is enabled */\n erc8004Enabled: boolean;\n /** ERC-8004 agent ID if enabled */\n erc8004AgentId?: string;\n}\n\n/**\n * Get reputation level from score\n */\nfunction getLevel(score: number): string {\n if (score >= 0.9) return 'Elite';\n if (score >= 0.7) return 'Trusted';\n if (score >= 0.5) return 'Established';\n if (score >= 0.3) return 'Developing';\n return 'New';\n}\n\n/**\n * Create an Xache client for reputation tools\n */\nfunction createClient(config: ReputationToolConfig): XacheClient {\n const chainPrefix = config.chain === 'solana' ? 'sol' : 'evm';\n const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}` as DID;\n\n return new XacheClient({\n apiUrl: config.apiUrl || 'https://api.xache.xyz',\n did,\n privateKey: config.privateKey,\n });\n}\n\n/**\n * Create a tool for checking your own reputation.\n *\n * @example\n * ```typescript\n * import { createReputationTool } from '@xache/langchain';\n *\n * const repTool = createReputationTool({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * });\n *\n * const tools = [repTool, ...];\n * ```\n */\nexport function createReputationTool(\n config: ReputationToolConfig\n): DynamicStructuredTool {\n const client = createClient(config);\n\n return new DynamicStructuredTool({\n name: 'xache_check_reputation',\n description:\n 'Check your current reputation score and status. ' +\n 'Returns your score (0-1), level, and ERC-8004 on-chain status. ' +\n 'Higher reputation means lower costs and more trust from other agents.',\n schema: z.object({}),\n func: async () => {\n const result = await client.reputation.getReputation();\n\n // Overall score is 0-100, normalize to 0-1\n const score = (result.overall || 0) / 100;\n const level = getLevel(score);\n\n let output = `Reputation Score: ${score.toFixed(2)}/1.00 (${level})\\n`;\n output += `Memory Quality: ${result.memoryQuality || 0}/100\\n`;\n output += `Contribution Success: ${result.contribSuccess || 0}/100\\n`;\n output += `Economic Value: ${result.economicValue || 0}/100\\n`;\n\n // Check ERC-8004 status separately\n try {\n const erc8004Status = await client.reputation.getERC8004Status();\n if (erc8004Status.enabled) {\n output += `ERC-8004 Status: Enabled\\n`;\n output += 'Your reputation is verifiable on-chain!';\n } else {\n output += 'ERC-8004 Status: Not enabled\\n';\n output += 'Enable ERC-8004 to make your reputation portable and verifiable.';\n }\n } catch {\n output += 'ERC-8004 Status: Unknown';\n }\n\n return output;\n },\n });\n}\n\n/**\n * Class-based reputation tool (alternative API)\n */\nexport class XacheReputationTool {\n private tool: DynamicStructuredTool;\n\n constructor(config: ReputationToolConfig) {\n this.tool = createReputationTool(config);\n }\n\n asTool(): DynamicStructuredTool {\n return this.tool;\n }\n}\n\n/**\n * Utility class for checking reputation of any agent.\n *\n * @example\n * ```typescript\n * import { XacheReputationChecker } from '@xache/langchain';\n *\n * const checker = new XacheReputationChecker({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * });\n *\n * const rep = await checker.check('did:agent:evm:0xOtherAgent...');\n * if (rep.score >= 0.5) {\n * console.log('Agent is trustworthy');\n * }\n * ```\n */\nexport class XacheReputationChecker {\n private client: XacheClient;\n\n constructor(config: ReputationToolConfig) {\n this.client = createClient(config);\n }\n\n /**\n * Check an agent's reputation\n */\n async check(agentDid: string): Promise<ReputationResult> {\n const result = await this.client.reputation.getReputation(agentDid as DID);\n\n // Overall score is 0-100, normalize to 0-1\n const score = (result.overall || 0) / 100;\n\n // Try to get ERC-8004 status\n let erc8004Enabled = false;\n let erc8004AgentId: string | undefined;\n try {\n const erc8004Status = await this.client.reputation.getERC8004Status();\n erc8004Enabled = erc8004Status.enabled;\n } catch {\n // ERC-8004 status not available\n }\n\n return {\n score,\n level: getLevel(score),\n totalContributions: 0, // Not available in current API\n totalPayments: 0, // Not available in current API\n erc8004Enabled,\n erc8004AgentId,\n };\n }\n\n /**\n * Check if an agent meets minimum reputation threshold\n */\n async meetsThreshold(agentDid: string, minScore: number): Promise<boolean> {\n const result = await this.check(agentDid);\n return result.score >= minScore;\n }\n}\n","/**\n * Xache Knowledge Graph for LangChain.js\n * Extract, query, and manage entities/relationships in a privacy-preserving knowledge graph\n */\n\nimport { DynamicStructuredTool } from '@langchain/core/tools';\nimport { BaseRetriever, BaseRetrieverInput } from '@langchain/core/retrievers';\nimport { Document } from '@langchain/core/documents';\nimport { CallbackManagerForRetrieverRun } from '@langchain/core/callbacks/manager';\nimport { z } from 'zod';\nimport {\n XacheClient,\n DID,\n type LLMProvider,\n type LLMApiFormat,\n type SubjectContext,\n} from '@xache/sdk';\n\n// =============================================================================\n// Configuration\n// =============================================================================\n\nexport interface GraphToolConfig {\n /** Wallet address for authentication */\n walletAddress: string;\n /** Private key for signing */\n privateKey: string;\n /** API URL (defaults to https://api.xache.xyz) */\n apiUrl?: string;\n /** Chain: 'base' or 'solana' */\n chain?: 'base' | 'solana';\n /** Subject context for graph scoping (defaults to GLOBAL) */\n subject?: SubjectContext;\n /** LLM provider for extract/ask (api-key mode) */\n llmProvider?: LLMProvider;\n /** LLM API key */\n llmApiKey?: string;\n /** LLM model override */\n llmModel?: string;\n /** LLM endpoint URL (endpoint mode) */\n llmEndpoint?: string;\n /** LLM auth token (endpoint mode) */\n llmAuthToken?: string;\n /** LLM API format (endpoint mode, default: openai) */\n llmFormat?: LLMApiFormat;\n}\n\nfunction createClient(config: GraphToolConfig): XacheClient {\n const chainPrefix = config.chain === 'solana' ? 'sol' : 'evm';\n const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}` as DID;\n\n return new XacheClient({\n apiUrl: config.apiUrl || 'https://api.xache.xyz',\n did,\n privateKey: config.privateKey,\n });\n}\n\nfunction getSubject(config: GraphToolConfig): SubjectContext {\n return config.subject || { scope: 'GLOBAL' };\n}\n\nfunction buildLLMConfig(config: GraphToolConfig): Record<string, unknown> {\n if (config.llmEndpoint) {\n return {\n type: 'endpoint' as const,\n url: config.llmEndpoint,\n authToken: config.llmAuthToken,\n format: config.llmFormat || 'openai',\n model: config.llmModel,\n };\n } else if (config.llmApiKey && config.llmProvider) {\n return {\n type: 'api-key' as const,\n provider: config.llmProvider,\n apiKey: config.llmApiKey,\n model: config.llmModel,\n };\n } else {\n return {\n type: 'xache-managed' as const,\n provider: 'anthropic',\n model: config.llmModel,\n };\n }\n}\n\n// =============================================================================\n// Factory Functions\n// =============================================================================\n\n/**\n * Create a tool for extracting entities/relationships from agent traces.\n *\n * @example\n * ```typescript\n * const extractTool = createGraphExtractTool({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * llmProvider: 'anthropic',\n * llmApiKey: 'sk-ant-...',\n * });\n * ```\n */\nexport function createGraphExtractTool(\n config: GraphToolConfig\n): DynamicStructuredTool {\n const client = createClient(config);\n const subject = getSubject(config);\n\n return new DynamicStructuredTool({\n name: 'xache_graph_extract',\n description:\n 'Extract entities and relationships from text into the knowledge graph. ' +\n 'Identifies people, organizations, tools, concepts and their connections.',\n schema: z.object({\n trace: z.string().describe('The text/trace to extract entities from'),\n contextHint: z.string().optional().describe('Domain hint (e.g., \"engineering\", \"customer-support\")'),\n }),\n func: async ({ trace, contextHint }) => {\n const result = await client.graph.extract({\n trace,\n llmConfig: buildLLMConfig(config) as any,\n subject,\n options: {\n contextHint,\n confidenceThreshold: 0.7,\n },\n });\n\n const entities = result.entities || [];\n const relationships = result.relationships || [];\n\n if (entities.length === 0 && relationships.length === 0) {\n return 'No entities or relationships extracted.';\n }\n\n let output = `Extracted ${entities.length} entities, ${relationships.length} relationships.\\n`;\n for (const e of entities) {\n output += ` Entity: ${e.name} [${e.type}]${e.isNew ? ' (new)' : ''}\\n`;\n }\n for (const r of relationships) {\n output += ` Rel: ${r.from} → ${r.type} → ${r.to}\\n`;\n }\n return output;\n },\n });\n}\n\n/**\n * Create a tool for querying the knowledge graph around a specific entity.\n */\nexport function createGraphQueryTool(\n config: GraphToolConfig\n): DynamicStructuredTool {\n const client = createClient(config);\n const subject = getSubject(config);\n\n return new DynamicStructuredTool({\n name: 'xache_graph_query',\n description:\n 'Query the knowledge graph around a specific entity. ' +\n 'Returns connected entities and relationships within the specified depth.',\n schema: z.object({\n startEntity: z.string().describe('Name of the entity to start from'),\n depth: z.number().optional().default(2).describe('Number of hops (default: 2)'),\n }),\n func: async ({ startEntity, depth }) => {\n const graph = await client.graph.query({\n subject,\n startEntity,\n depth: depth || 2,\n });\n\n const data = graph.toJSON();\n if (data.entities.length === 0) {\n return `No entities found connected to \"${startEntity}\".`;\n }\n\n let output = `Subgraph: ${data.entities.length} entities, ${data.relationships.length} relationships\\n`;\n for (const e of data.entities) {\n output += ` ${e.name} [${e.type}]`;\n if (e.summary) output += ` — ${e.summary.substring(0, 80)}`;\n output += '\\n';\n }\n return output;\n },\n });\n}\n\n/**\n * Create a tool for asking natural language questions about the knowledge graph.\n */\nexport function createGraphAskTool(\n config: GraphToolConfig\n): DynamicStructuredTool {\n const client = createClient(config);\n const subject = getSubject(config);\n\n return new DynamicStructuredTool({\n name: 'xache_graph_ask',\n description:\n 'Ask a natural language question about the knowledge graph. ' +\n 'Uses LLM to analyze entities and relationships and provide an answer.',\n schema: z.object({\n question: z.string().describe('The question to ask about the knowledge graph'),\n }),\n func: async ({ question }) => {\n const answer = await client.graph.ask({\n subject,\n question,\n llmConfig: buildLLMConfig(config) as any,\n });\n\n let output = `Answer: ${answer.answer}\\nConfidence: ${(answer.confidence * 100).toFixed(0)}%`;\n if (answer.sources?.length > 0) {\n output += '\\nSources: ' + answer.sources.map(s => `${s.name} [${s.type}]`).join(', ');\n }\n return output;\n },\n });\n}\n\n/**\n * Create a tool for adding entities to the knowledge graph.\n */\nexport function createGraphAddEntityTool(\n config: GraphToolConfig\n): DynamicStructuredTool {\n const client = createClient(config);\n const subject = getSubject(config);\n\n return new DynamicStructuredTool({\n name: 'xache_graph_add_entity',\n description:\n 'Add an entity to the knowledge graph. ' +\n 'Creates a person, organization, tool, concept, or other entity type.',\n schema: z.object({\n name: z.string().describe('Entity name'),\n type: z.string().describe('Entity type (person, organization, tool, concept, etc.)'),\n summary: z.string().optional().describe('Brief description'),\n attributes: z.record(z.string(), z.unknown()).optional().describe('Key-value attributes'),\n }),\n func: async ({ name, type, summary, attributes }) => {\n const entity = await client.graph.addEntity({\n subject,\n name,\n type,\n summary,\n attributes,\n });\n return `Created entity \"${entity.name}\" [${entity.type}], key: ${entity.key}`;\n },\n });\n}\n\n/**\n * Create a tool for adding relationships between entities.\n */\nexport function createGraphAddRelationshipTool(\n config: GraphToolConfig\n): DynamicStructuredTool {\n const client = createClient(config);\n const subject = getSubject(config);\n\n return new DynamicStructuredTool({\n name: 'xache_graph_add_relationship',\n description:\n 'Create a relationship between two entities in the knowledge graph.',\n schema: z.object({\n from: z.string().describe('Source entity name'),\n to: z.string().describe('Target entity name'),\n type: z.string().describe('Relationship type (works_at, knows, uses, manages, etc.)'),\n description: z.string().optional().describe('Relationship description'),\n }),\n func: async ({ from, to, type, description }) => {\n const rel = await client.graph.addRelationship({\n subject,\n from,\n to,\n type,\n description,\n });\n return `Created relationship: ${from} → ${rel.type} → ${to}`;\n },\n });\n}\n\n/**\n * Create a tool for loading the full knowledge graph.\n */\nexport function createGraphLoadTool(\n config: GraphToolConfig\n): DynamicStructuredTool {\n const client = createClient(config);\n const subject = getSubject(config);\n\n return new DynamicStructuredTool({\n name: 'xache_graph_load',\n description:\n 'Load the full knowledge graph. Returns all entities and relationships. ' +\n 'Optionally filter by entity type or load a historical snapshot.',\n schema: z.object({\n entityTypes: z.array(z.string()).optional().describe('Filter to specific entity types'),\n validAt: z.string().optional().describe('Load graph as it existed at this time (ISO8601)'),\n }),\n func: async ({ entityTypes, validAt }) => {\n const graph = await client.graph.load({\n subject,\n entityTypes,\n validAt,\n });\n\n const data = graph.toJSON();\n if (data.entities.length === 0) {\n return 'Knowledge graph is empty.';\n }\n\n let output = `Knowledge graph: ${data.entities.length} entities, ${data.relationships.length} relationships\\n`;\n for (const e of data.entities) {\n output += ` ${e.name} [${e.type}]`;\n if (e.summary) output += ` — ${e.summary.substring(0, 80)}`;\n output += '\\n';\n }\n return output;\n },\n });\n}\n\n/**\n * Create a tool for merging two entities in the knowledge graph.\n */\nexport function createGraphMergeEntitiesTool(\n config: GraphToolConfig\n): DynamicStructuredTool {\n const client = createClient(config);\n const subject = getSubject(config);\n\n return new DynamicStructuredTool({\n name: 'xache_graph_merge_entities',\n description:\n 'Merge two entities into one. The source entity is superseded and the target ' +\n 'entity is updated with merged attributes. Relationships are transferred.',\n schema: z.object({\n sourceName: z.string().describe('Entity to merge FROM (will be superseded)'),\n targetName: z.string().describe('Entity to merge INTO (will be updated)'),\n }),\n func: async ({ sourceName, targetName }) => {\n const merged = await client.graph.mergeEntities({\n subject,\n sourceName,\n targetName,\n });\n return `Merged \"${sourceName}\" into \"${targetName}\". Result: ${merged.name} [${merged.type}] (v${merged.version})`;\n },\n });\n}\n\n/**\n * Create a tool for getting the version history of an entity.\n */\nexport function createGraphEntityHistoryTool(\n config: GraphToolConfig\n): DynamicStructuredTool {\n const client = createClient(config);\n const subject = getSubject(config);\n\n return new DynamicStructuredTool({\n name: 'xache_graph_entity_history',\n description:\n 'Get the full version history of an entity. Shows how the entity has changed over time.',\n schema: z.object({\n name: z.string().describe('Entity name to look up history for'),\n }),\n func: async ({ name }) => {\n const versions = await client.graph.getEntityHistory({\n subject,\n name,\n });\n\n if (versions.length === 0) {\n return `No history found for entity \"${name}\".`;\n }\n\n let output = `History for \"${name}\": ${versions.length} version(s)\\n`;\n for (const v of versions) {\n output += ` v${v.version} — ${v.name} [${v.type}]`;\n if (v.summary) output += ` | ${v.summary.substring(0, 80)}`;\n output += `\\n Valid: ${v.validFrom}${v.validTo ? ` → ${v.validTo}` : ' → current'}\\n`;\n }\n return output;\n },\n });\n}\n\n// =============================================================================\n// Class Wrappers\n// =============================================================================\n\n/**\n * Class wrapper for graph extract tool\n */\nexport class XacheGraphExtractTool {\n private tool: DynamicStructuredTool;\n\n constructor(config: GraphToolConfig) {\n this.tool = createGraphExtractTool(config);\n }\n\n asTool(): DynamicStructuredTool {\n return this.tool;\n }\n}\n\n/**\n * Class wrapper for graph query tool\n */\nexport class XacheGraphQueryTool {\n private tool: DynamicStructuredTool;\n\n constructor(config: GraphToolConfig) {\n this.tool = createGraphQueryTool(config);\n }\n\n asTool(): DynamicStructuredTool {\n return this.tool;\n }\n}\n\n/**\n * Class wrapper for graph ask tool\n */\nexport class XacheGraphAskTool {\n private tool: DynamicStructuredTool;\n\n constructor(config: GraphToolConfig) {\n this.tool = createGraphAskTool(config);\n }\n\n asTool(): DynamicStructuredTool {\n return this.tool;\n }\n}\n\n/**\n * Class wrapper for graph load tool\n */\nexport class XacheGraphLoadTool {\n private tool: DynamicStructuredTool;\n\n constructor(config: GraphToolConfig) {\n this.tool = createGraphLoadTool(config);\n }\n\n asTool(): DynamicStructuredTool {\n return this.tool;\n }\n}\n\n/**\n * Class wrapper for graph merge entities tool\n */\nexport class XacheGraphMergeEntitiesTool {\n private tool: DynamicStructuredTool;\n\n constructor(config: GraphToolConfig) {\n this.tool = createGraphMergeEntitiesTool(config);\n }\n\n asTool(): DynamicStructuredTool {\n return this.tool;\n }\n}\n\n/**\n * Class wrapper for graph entity history tool\n */\nexport class XacheGraphEntityHistoryTool {\n private tool: DynamicStructuredTool;\n\n constructor(config: GraphToolConfig) {\n this.tool = createGraphEntityHistoryTool(config);\n }\n\n asTool(): DynamicStructuredTool {\n return this.tool;\n }\n}\n\n// =============================================================================\n// Graph Retriever\n// =============================================================================\n\nexport interface XacheGraphRetrieverConfig extends BaseRetrieverInput {\n /** Wallet address for authentication */\n walletAddress: string;\n /** Private key for signing */\n privateKey: string;\n /** API URL (defaults to https://api.xache.xyz) */\n apiUrl?: string;\n /** Chain: 'base' or 'solana' */\n chain?: 'base' | 'solana';\n /** Subject context for graph scoping */\n subject?: SubjectContext;\n /** Starting entity for subgraph query (optional — if not set, loads full graph) */\n startEntity?: string;\n /** Depth for subgraph query (default: 2) */\n depth?: number;\n /** Max results to return */\n k?: number;\n}\n\n/**\n * Retriever that fetches documents from the Xache knowledge graph.\n * Each entity becomes a Document with its name, type, and summary.\n *\n * @example\n * ```typescript\n * const retriever = new XacheGraphRetriever({\n * walletAddress: '0x...',\n * privateKey: '0x...',\n * k: 10,\n * });\n *\n * const docs = await retriever.getRelevantDocuments('engineering team');\n * ```\n */\nexport class XacheGraphRetriever extends BaseRetriever {\n lc_namespace = ['xache', 'graph_retriever'];\n\n static lc_name() {\n return 'XacheGraphRetriever';\n }\n\n private client: XacheClient;\n private subject: SubjectContext;\n private startEntity?: string;\n private depth: number;\n private k: number;\n\n constructor(config: XacheGraphRetrieverConfig) {\n super(config);\n\n const chainPrefix = config.chain === 'solana' ? 'sol' : 'evm';\n const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}` as DID;\n\n this.client = new XacheClient({\n apiUrl: config.apiUrl || 'https://api.xache.xyz',\n did,\n privateKey: config.privateKey,\n });\n\n this.subject = config.subject || { scope: 'GLOBAL' };\n this.startEntity = config.startEntity;\n this.depth = config.depth ?? 2;\n this.k = config.k ?? 10;\n }\n\n async _getRelevantDocuments(\n query: string,\n _runManager?: CallbackManagerForRetrieverRun,\n ): Promise<Document[]> {\n // Load graph (full or subgraph)\n let graph;\n if (this.startEntity) {\n graph = await this.client.graph.query({\n subject: this.subject,\n startEntity: this.startEntity,\n depth: this.depth,\n });\n } else {\n graph = await this.client.graph.load({ subject: this.subject });\n }\n\n const data = graph.toJSON();\n const queryLower = query.toLowerCase();\n\n // Score entities by relevance to query\n const scored = data.entities.map(entity => {\n let score = 0;\n const nameLower = entity.name.toLowerCase();\n const summaryLower = (entity.summary || '').toLowerCase();\n\n if (nameLower.includes(queryLower)) score += 3;\n if (summaryLower.includes(queryLower)) score += 2;\n\n // Check individual query terms\n const terms = queryLower.split(/\\s+/);\n for (const term of terms) {\n if (nameLower.includes(term)) score += 1;\n if (summaryLower.includes(term)) score += 0.5;\n }\n\n return { entity, score };\n });\n\n // Sort by score, take top k\n scored.sort((a, b) => b.score - a.score);\n const topEntities = scored.slice(0, this.k);\n\n return topEntities.map(({ entity }) => {\n const content = [\n `Name: ${entity.name}`,\n `Type: ${entity.type}`,\n entity.summary ? `Summary: ${entity.summary}` : null,\n ].filter(Boolean).join('\\n');\n\n return new Document({\n pageContent: content,\n metadata: {\n source: 'xache-graph',\n entityKey: entity.key,\n entityName: entity.name,\n entityType: entity.type,\n storageKey: entity.storageKey,\n },\n });\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,oBAAuE;;;ACAvE,0BAA2C;AAC3C,sBAKO;AACP,iBAAiC;AACjC,oBAA2B;AA6CpB,IAAM,0BAAN,cAAsC,+CAA2B;AAAA,EAUtE,YAAY,QAAuC;AACjD,UAAM;AAVR,wBAAe,CAAC,SAAS,cAAc;AAIvC,SAAQ,WAA0B,CAAC;AACnC,SAAQ,cAAc;AAOpB,UAAM,cAAc,OAAO,UAAU,WAAW,QAAQ;AACxD,UAAM,MAAM,aAAa,WAAW,IAAI,OAAO,cAAc,YAAY,CAAC;AAE1E,SAAK,SAAS,IAAI,uBAAY;AAAA,MAC5B,QAAQ,OAAO,UAAU;AAAA,MACzB;AAAA,MACA,YAAY,OAAO;AAAA,MACnB,SAAS,OAAO;AAAA,MAChB,OAAO,OAAO;AAAA,IAChB,CAAC;AAGD,SAAK,YAAY,OAAO,aAAa,iBAAa,0BAAW,CAAC;AAC9D,SAAK,cAAc,OAAO,eAAe;AACzC,SAAK,WAAW,OAAO,YAAY;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,cAAsC;AAC1C,QAAI,CAAC,KAAK,aAAa;AACrB,YAAM,KAAK,aAAa;AAAA,IAC1B;AACA,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,WAAW,SAAqC;AACpD,S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AM,YAAY,OAAO,KAAK,YAAY;AAC1C,YAAM,gBAAgB,OAAO,WAAW,IAAI,YAAY;AAExD,UAAI,UAAU,SAAS,UAAU,EAAG,UAAS;AAC7C,UAAI,aAAa,SAAS,UAAU,EAAG,UAAS;AAGhD,YAAM,QAAQ,WAAW,MAAM,KAAK;AACpC,iBAAW,QAAQ,OAAO;AACxB,YAAI,UAAU,SAAS,IAAI,EAAG,UAAS;AACvC,YAAI,aAAa,SAAS,IAAI,EAAG,UAAS;AAAA,MAC5C;AAEA,aAAO,EAAE,QAAQ,MAAM;AAAA,IACzB,CAAC;AAGD,WAAO,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AACvC,UAAM,cAAc,OAAO,MAAM,GAAG,KAAK,CAAC;AAE1C,WAAO,YAAY,IAAI,CAAC,EAAE,OAAO,MAAM;AACrC,YAAM,UAAU;AAAA,QACd,SAAS,OAAO,IAAI;AAAA,QACpB,SAAS,OAAO,IAAI;AAAA,QACpB,OAAO,UAAU,YAAY,OAAO,OAAO,KAAK;AAAA,MAClD,EAAE,OAAO,OAAO,EAAE,KAAK,IAAI;AAE3B,aAAO,IAAI,2BAAS;AAAA,QAClB,aAAa;AAAA,QACb,UAAU;AAAA,UACR,QAAQ;AAAA,UACR,WAAW,OAAO;AAAA,UAClB,YAAY,OAAO;AAAA,UACnB,YAAY,OAAO;AAAA,UACnB,YAAY,OAAO;AAAA,QACrB;AAAA,MACF,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACF;","names":["import_sdk","import_sdk","import_sdk","import_tools","import_zod","import_sdk","createClient","import_tools","import_retrievers","import_documents","import_zod","import_sdk","createClient"]}