@xache/langchain 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +177 -0
- package/dist/index.d.mts +457 -0
- package/dist/index.d.ts +457 -0
- package/dist/index.js +567 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +533 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +68 -0
- package/src/chat_history.ts +232 -0
- package/src/collective.ts +195 -0
- package/src/extraction.ts +172 -0
- package/src/index.ts +59 -0
- package/src/memory.ts +121 -0
- package/src/reputation.ts +195 -0
- package/src/retriever.ts +100 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
XacheChatMessageHistory: () => XacheChatMessageHistory,
|
|
24
|
+
XacheCollectiveContributeTool: () => XacheCollectiveContributeTool,
|
|
25
|
+
XacheCollectiveQueryTool: () => XacheCollectiveQueryTool,
|
|
26
|
+
XacheConversationBufferMemory: () => XacheConversationBufferMemory,
|
|
27
|
+
XacheExtractor: () => XacheExtractor,
|
|
28
|
+
XacheMemory: () => XacheMemory,
|
|
29
|
+
XacheReputationChecker: () => XacheReputationChecker,
|
|
30
|
+
XacheReputationTool: () => XacheReputationTool,
|
|
31
|
+
XacheRetriever: () => XacheRetriever,
|
|
32
|
+
createCollectiveContributeTool: () => createCollectiveContributeTool,
|
|
33
|
+
createCollectiveQueryTool: () => createCollectiveQueryTool,
|
|
34
|
+
createReputationTool: () => createReputationTool
|
|
35
|
+
});
|
|
36
|
+
module.exports = __toCommonJS(index_exports);
|
|
37
|
+
|
|
38
|
+
// src/memory.ts
|
|
39
|
+
var import_memory = require("@langchain/core/memory");
|
|
40
|
+
|
|
41
|
+
// src/chat_history.ts
|
|
42
|
+
var import_chat_history = require("@langchain/core/chat_history");
|
|
43
|
+
var import_messages = require("@langchain/core/messages");
|
|
44
|
+
var import_sdk = require("@xache/sdk");
|
|
45
|
+
var import_crypto = require("crypto");
|
|
46
|
+
var XacheChatMessageHistory = class extends import_chat_history.BaseListChatMessageHistory {
|
|
47
|
+
constructor(config) {
|
|
48
|
+
super();
|
|
49
|
+
this.lc_namespace = ["xache", "chat_history"];
|
|
50
|
+
this.messages = [];
|
|
51
|
+
this.initialized = false;
|
|
52
|
+
const chainPrefix = config.chain === "solana" ? "sol" : "evm";
|
|
53
|
+
const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}`;
|
|
54
|
+
this.client = new import_sdk.XacheClient({
|
|
55
|
+
apiUrl: config.apiUrl || "https://api.xache.xyz",
|
|
56
|
+
did,
|
|
57
|
+
privateKey: config.privateKey,
|
|
58
|
+
timeout: config.timeout,
|
|
59
|
+
debug: config.debug
|
|
60
|
+
});
|
|
61
|
+
this.sessionId = config.sessionId || `langchain-${(0, import_crypto.randomUUID)()}`;
|
|
62
|
+
this.maxMessages = config.maxMessages ?? 1e3;
|
|
63
|
+
this.pageSize = config.pageSize ?? 100;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Get all messages in the history
|
|
67
|
+
*/
|
|
68
|
+
async getMessages() {
|
|
69
|
+
if (!this.initialized) {
|
|
70
|
+
await this.loadMessages();
|
|
71
|
+
}
|
|
72
|
+
return this.messages;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Add a message to the history
|
|
76
|
+
*/
|
|
77
|
+
async addMessage(message) {
|
|
78
|
+
this.messages.push(message);
|
|
79
|
+
const role = this.getMessageRole(message);
|
|
80
|
+
const content = typeof message.content === "string" ? message.content : JSON.stringify(message.content);
|
|
81
|
+
await this.client.memory.store({
|
|
82
|
+
data: {
|
|
83
|
+
role,
|
|
84
|
+
content,
|
|
85
|
+
sessionId: this.sessionId,
|
|
86
|
+
timestamp: Date.now()
|
|
87
|
+
},
|
|
88
|
+
storageTier: "hot",
|
|
89
|
+
context: `chat:${this.sessionId}`,
|
|
90
|
+
tags: ["chat", "message", role],
|
|
91
|
+
metadata: {
|
|
92
|
+
sessionId: this.sessionId,
|
|
93
|
+
role
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Add a user message
|
|
99
|
+
*/
|
|
100
|
+
async addUserMessage(message) {
|
|
101
|
+
await this.addMessage(new import_messages.HumanMessage(message));
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Add an AI message
|
|
105
|
+
*/
|
|
106
|
+
async addAIMessage(message) {
|
|
107
|
+
await this.addMessage(new import_messages.AIMessage(message));
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Clear all messages from history
|
|
111
|
+
*/
|
|
112
|
+
async clear() {
|
|
113
|
+
this.messages = [];
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Load messages from Xache storage with pagination support
|
|
117
|
+
*/
|
|
118
|
+
async loadMessages() {
|
|
119
|
+
try {
|
|
120
|
+
const allMemories = [];
|
|
121
|
+
let offset = 0;
|
|
122
|
+
const effectiveMax = this.maxMessages === -1 ? Infinity : this.maxMessages;
|
|
123
|
+
while (allMemories.length < effectiveMax) {
|
|
124
|
+
const result = await this.client.memory.list({
|
|
125
|
+
context: `chat:${this.sessionId}`,
|
|
126
|
+
limit: Math.min(this.pageSize, effectiveMax - allMemories.length),
|
|
127
|
+
offset
|
|
128
|
+
});
|
|
129
|
+
const memories = Array.isArray(result?.memories) ? result.memories : [];
|
|
130
|
+
if (memories.length === 0) break;
|
|
131
|
+
allMemories.push(...memories);
|
|
132
|
+
offset += memories.length;
|
|
133
|
+
if (memories.length < this.pageSize) break;
|
|
134
|
+
}
|
|
135
|
+
const sortedMemories = [...allMemories].sort((a, b) => {
|
|
136
|
+
const tsA = new Date(a.created_at || 0).getTime();
|
|
137
|
+
const tsB = new Date(b.created_at || 0).getTime();
|
|
138
|
+
return tsA - tsB;
|
|
139
|
+
});
|
|
140
|
+
this.messages = [];
|
|
141
|
+
for (const m of sortedMemories) {
|
|
142
|
+
try {
|
|
143
|
+
const full = await this.client.memory.retrieve({
|
|
144
|
+
storageKey: m.storage_key
|
|
145
|
+
});
|
|
146
|
+
const data = full.data;
|
|
147
|
+
if (data && data.content) {
|
|
148
|
+
switch (data.role) {
|
|
149
|
+
case "human":
|
|
150
|
+
case "user":
|
|
151
|
+
this.messages.push(new import_messages.HumanMessage(data.content));
|
|
152
|
+
break;
|
|
153
|
+
case "ai":
|
|
154
|
+
case "assistant":
|
|
155
|
+
this.messages.push(new import_messages.AIMessage(data.content));
|
|
156
|
+
break;
|
|
157
|
+
case "system":
|
|
158
|
+
this.messages.push(new import_messages.SystemMessage(data.content));
|
|
159
|
+
break;
|
|
160
|
+
default:
|
|
161
|
+
this.messages.push(new import_messages.HumanMessage(data.content));
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
} catch (error) {
|
|
165
|
+
console.debug?.(`[XacheChatMessageHistory] Failed to parse message: ${error.message}`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
this.initialized = true;
|
|
169
|
+
} catch (error) {
|
|
170
|
+
console.debug?.(`[XacheChatMessageHistory] No existing messages found: ${error.message}`);
|
|
171
|
+
this.messages = [];
|
|
172
|
+
this.initialized = true;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
getMessageRole(message) {
|
|
176
|
+
if (message instanceof import_messages.HumanMessage) return "human";
|
|
177
|
+
if (message instanceof import_messages.AIMessage) return "ai";
|
|
178
|
+
if (message instanceof import_messages.SystemMessage) return "system";
|
|
179
|
+
return "unknown";
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
// src/memory.ts
|
|
184
|
+
var XacheMemory = class extends import_memory.BaseMemory {
|
|
185
|
+
constructor(config) {
|
|
186
|
+
super();
|
|
187
|
+
this.lc_namespace = ["xache", "memory"];
|
|
188
|
+
this.chatHistory = new XacheChatMessageHistory(config);
|
|
189
|
+
this.inputKey = config.inputKey || "input";
|
|
190
|
+
this.outputKey = config.outputKey || "output";
|
|
191
|
+
this.memoryKey = config.memoryKey || "history";
|
|
192
|
+
this.returnMessages = config.returnMessages ?? false;
|
|
193
|
+
}
|
|
194
|
+
get memoryKeys() {
|
|
195
|
+
return [this.memoryKey];
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Load memory variables
|
|
199
|
+
*/
|
|
200
|
+
async loadMemoryVariables(_values) {
|
|
201
|
+
const messages = await this.chatHistory.getMessages();
|
|
202
|
+
if (this.returnMessages) {
|
|
203
|
+
return { [this.memoryKey]: messages };
|
|
204
|
+
}
|
|
205
|
+
const history = messages.map((m) => {
|
|
206
|
+
const role = m._getType() === "human" ? "Human" : "AI";
|
|
207
|
+
const content = typeof m.content === "string" ? m.content : JSON.stringify(m.content);
|
|
208
|
+
return `${role}: ${content}`;
|
|
209
|
+
}).join("\n");
|
|
210
|
+
return { [this.memoryKey]: history };
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Save context from this conversation to buffer
|
|
214
|
+
*/
|
|
215
|
+
async saveContext(inputValues, outputValues) {
|
|
216
|
+
const input = inputValues[this.inputKey];
|
|
217
|
+
const output = outputValues[this.outputKey];
|
|
218
|
+
if (input) {
|
|
219
|
+
await this.chatHistory.addUserMessage(String(input));
|
|
220
|
+
}
|
|
221
|
+
if (output) {
|
|
222
|
+
await this.chatHistory.addAIMessage(String(output));
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Clear memory contents
|
|
227
|
+
*/
|
|
228
|
+
async clear() {
|
|
229
|
+
await this.chatHistory.clear();
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
var XacheConversationBufferMemory = class extends XacheMemory {
|
|
233
|
+
constructor() {
|
|
234
|
+
super(...arguments);
|
|
235
|
+
this.lc_namespace = ["xache", "memory", "buffer"];
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
// src/retriever.ts
|
|
240
|
+
var import_retrievers = require("@langchain/core/retrievers");
|
|
241
|
+
var import_documents = require("@langchain/core/documents");
|
|
242
|
+
var import_sdk2 = require("@xache/sdk");
|
|
243
|
+
var XacheRetriever = class extends import_retrievers.BaseRetriever {
|
|
244
|
+
constructor(config) {
|
|
245
|
+
super(config);
|
|
246
|
+
this.lc_namespace = ["xache", "retriever"];
|
|
247
|
+
const chainPrefix = config.chain === "solana" ? "sol" : "evm";
|
|
248
|
+
const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}`;
|
|
249
|
+
this.client = new import_sdk2.XacheClient({
|
|
250
|
+
apiUrl: config.apiUrl || "https://api.xache.xyz",
|
|
251
|
+
did,
|
|
252
|
+
privateKey: config.privateKey
|
|
253
|
+
});
|
|
254
|
+
this.k = config.k ?? 5;
|
|
255
|
+
this.filterContext = config.context;
|
|
256
|
+
}
|
|
257
|
+
static lc_name() {
|
|
258
|
+
return "XacheRetriever";
|
|
259
|
+
}
|
|
260
|
+
async _getRelevantDocuments(_query, _runManager) {
|
|
261
|
+
const result = await this.client.memory.list({
|
|
262
|
+
context: this.filterContext,
|
|
263
|
+
limit: this.k
|
|
264
|
+
});
|
|
265
|
+
const memories = result.memories || [];
|
|
266
|
+
return memories.map(
|
|
267
|
+
(m) => new import_documents.Document({
|
|
268
|
+
pageContent: m.context || "",
|
|
269
|
+
metadata: {
|
|
270
|
+
storageKey: m.storage_key,
|
|
271
|
+
context: m.context,
|
|
272
|
+
tier: m.storage_tier,
|
|
273
|
+
createdAt: m.created_at,
|
|
274
|
+
size: m.size_bytes
|
|
275
|
+
}
|
|
276
|
+
})
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
// src/extraction.ts
|
|
282
|
+
var import_sdk3 = require("@xache/sdk");
|
|
283
|
+
var XacheExtractor = class {
|
|
284
|
+
constructor(config) {
|
|
285
|
+
const mode = config.mode || "xache-managed";
|
|
286
|
+
if (mode === "api-key" && !config.llmApiKey) {
|
|
287
|
+
throw new Error('llmApiKey is required when mode is "api-key"');
|
|
288
|
+
}
|
|
289
|
+
const chainPrefix = config.chain === "solana" ? "sol" : "evm";
|
|
290
|
+
const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}`;
|
|
291
|
+
this.client = new import_sdk3.XacheClient({
|
|
292
|
+
apiUrl: config.apiUrl || "https://api.xache.xyz",
|
|
293
|
+
did,
|
|
294
|
+
privateKey: config.privateKey,
|
|
295
|
+
timeout: config.timeout,
|
|
296
|
+
debug: config.debug
|
|
297
|
+
});
|
|
298
|
+
this.mode = mode;
|
|
299
|
+
this.llmApiKey = config.llmApiKey;
|
|
300
|
+
this.llmProvider = config.llmProvider || "anthropic";
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Extract memories from a conversation trace
|
|
304
|
+
*/
|
|
305
|
+
async extract(trace, options) {
|
|
306
|
+
const llmConfig = this.mode === "xache-managed" ? { type: "xache-managed", provider: "anthropic" } : {
|
|
307
|
+
type: "api-key",
|
|
308
|
+
provider: this.llmProvider || "anthropic",
|
|
309
|
+
apiKey: this.llmApiKey || ""
|
|
310
|
+
};
|
|
311
|
+
const result = await this.client.extraction.extract({
|
|
312
|
+
trace,
|
|
313
|
+
llmConfig,
|
|
314
|
+
options: {
|
|
315
|
+
autoStore: options?.autoStore,
|
|
316
|
+
contextHint: options?.instructions
|
|
317
|
+
}
|
|
318
|
+
});
|
|
319
|
+
const minConfidence = options?.minConfidence ?? 0;
|
|
320
|
+
const memories = (result.extractions || []).filter((m) => (m.confidence || 1) >= minConfidence).map((m, index) => ({
|
|
321
|
+
content: m.reasoning || JSON.stringify(m.data) || "",
|
|
322
|
+
context: m.type || "extracted",
|
|
323
|
+
tags: Object.keys(m.data || {}),
|
|
324
|
+
confidence: m.confidence || 1,
|
|
325
|
+
memoryId: result.stored?.[index]
|
|
326
|
+
}));
|
|
327
|
+
return {
|
|
328
|
+
memories,
|
|
329
|
+
count: memories.length,
|
|
330
|
+
cost: 0,
|
|
331
|
+
// Cost is handled by x402
|
|
332
|
+
receiptId: result.metadata?.paymentReceiptId
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Extract from LangChain messages
|
|
337
|
+
*/
|
|
338
|
+
async extractFromMessages(messages, options) {
|
|
339
|
+
const trace = messages.map((m) => `${m.role}: ${m.content}`).join("\n");
|
|
340
|
+
return this.extract(trace, options);
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
// src/collective.ts
|
|
345
|
+
var import_tools = require("@langchain/core/tools");
|
|
346
|
+
var import_zod = require("zod");
|
|
347
|
+
var import_sdk4 = require("@xache/sdk");
|
|
348
|
+
async function generatePatternHash(pattern) {
|
|
349
|
+
const encoder = new TextEncoder();
|
|
350
|
+
const data = encoder.encode(pattern);
|
|
351
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
|
352
|
+
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
353
|
+
return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
354
|
+
}
|
|
355
|
+
function createClient(config) {
|
|
356
|
+
const chainPrefix = config.chain === "solana" ? "sol" : "evm";
|
|
357
|
+
const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}`;
|
|
358
|
+
return new import_sdk4.XacheClient({
|
|
359
|
+
apiUrl: config.apiUrl || "https://api.xache.xyz",
|
|
360
|
+
did,
|
|
361
|
+
privateKey: config.privateKey
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
function createCollectiveContributeTool(config) {
|
|
365
|
+
const client = createClient(config);
|
|
366
|
+
return new import_tools.DynamicStructuredTool({
|
|
367
|
+
name: "xache_collective_contribute",
|
|
368
|
+
description: "Contribute an insight or learning to the collective intelligence pool. Use this when you discover something valuable that could help other agents. You'll earn reputation for quality contributions.",
|
|
369
|
+
schema: import_zod.z.object({
|
|
370
|
+
insight: import_zod.z.string().describe("The insight or learning to contribute"),
|
|
371
|
+
domain: import_zod.z.string().describe("Domain/topic of the insight"),
|
|
372
|
+
evidence: import_zod.z.string().optional().describe("Supporting evidence"),
|
|
373
|
+
tags: import_zod.z.array(import_zod.z.string()).optional().describe("Tags for categorization")
|
|
374
|
+
}),
|
|
375
|
+
func: async ({ insight, domain, evidence, tags }) => {
|
|
376
|
+
const pattern = insight;
|
|
377
|
+
const patternHash = await generatePatternHash(pattern);
|
|
378
|
+
const tagsArray = tags || ["general"];
|
|
379
|
+
const result = await client.collective.contribute({
|
|
380
|
+
domain,
|
|
381
|
+
pattern,
|
|
382
|
+
patternHash,
|
|
383
|
+
tags: tagsArray,
|
|
384
|
+
metrics: {
|
|
385
|
+
successRate: 0.8,
|
|
386
|
+
// Default metrics for new contributions
|
|
387
|
+
sampleSize: 1,
|
|
388
|
+
confidence: 0.7
|
|
389
|
+
},
|
|
390
|
+
encryptedContentRef: evidence || ""
|
|
391
|
+
// Store evidence as encrypted ref
|
|
392
|
+
});
|
|
393
|
+
const heuristicId = result.heuristicId || "unknown";
|
|
394
|
+
const receiptId = result.receiptId || "unknown";
|
|
395
|
+
return `Contributed insight to '${domain}'. Heuristic ID: ${heuristicId}, Receipt: ${receiptId}`;
|
|
396
|
+
}
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
function createCollectiveQueryTool(config) {
|
|
400
|
+
const client = createClient(config);
|
|
401
|
+
return new import_tools.DynamicStructuredTool({
|
|
402
|
+
name: "xache_collective_query",
|
|
403
|
+
description: "Query the collective intelligence pool to learn from other agents. Use this when you need insights or knowledge from the community. Returns relevant contributions from other agents.",
|
|
404
|
+
schema: import_zod.z.object({
|
|
405
|
+
query: import_zod.z.string().describe("What to search for in the collective"),
|
|
406
|
+
domain: import_zod.z.string().optional().describe("Filter by domain"),
|
|
407
|
+
limit: import_zod.z.number().optional().default(5).describe("Number of results")
|
|
408
|
+
}),
|
|
409
|
+
func: async ({ query, domain, limit }) => {
|
|
410
|
+
const result = await client.collective.query({
|
|
411
|
+
queryText: query,
|
|
412
|
+
domain,
|
|
413
|
+
limit: limit || 5
|
|
414
|
+
});
|
|
415
|
+
const results = result.matches || [];
|
|
416
|
+
if (results.length === 0) {
|
|
417
|
+
return "No relevant insights found in the collective.";
|
|
418
|
+
}
|
|
419
|
+
let output = `Found ${results.length} insights:
|
|
420
|
+
`;
|
|
421
|
+
results.forEach((item, i) => {
|
|
422
|
+
const pattern = (item.pattern || "").slice(0, 200);
|
|
423
|
+
output += `
|
|
424
|
+
${i + 1}. ${pattern}`;
|
|
425
|
+
if (item.domain) {
|
|
426
|
+
output += ` [Domain: ${item.domain}]`;
|
|
427
|
+
}
|
|
428
|
+
if (item.relevanceScore) {
|
|
429
|
+
output += ` (Relevance: ${item.relevanceScore.toFixed(2)})`;
|
|
430
|
+
}
|
|
431
|
+
});
|
|
432
|
+
return output;
|
|
433
|
+
}
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
var XacheCollectiveContributeTool = class {
|
|
437
|
+
constructor(config) {
|
|
438
|
+
this.tool = createCollectiveContributeTool(config);
|
|
439
|
+
}
|
|
440
|
+
asTool() {
|
|
441
|
+
return this.tool;
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
var XacheCollectiveQueryTool = class {
|
|
445
|
+
constructor(config) {
|
|
446
|
+
this.tool = createCollectiveQueryTool(config);
|
|
447
|
+
}
|
|
448
|
+
asTool() {
|
|
449
|
+
return this.tool;
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
|
|
453
|
+
// src/reputation.ts
|
|
454
|
+
var import_tools2 = require("@langchain/core/tools");
|
|
455
|
+
var import_zod2 = require("zod");
|
|
456
|
+
var import_sdk5 = require("@xache/sdk");
|
|
457
|
+
function getLevel(score) {
|
|
458
|
+
if (score >= 0.9) return "Elite";
|
|
459
|
+
if (score >= 0.7) return "Trusted";
|
|
460
|
+
if (score >= 0.5) return "Established";
|
|
461
|
+
if (score >= 0.3) return "Developing";
|
|
462
|
+
return "New";
|
|
463
|
+
}
|
|
464
|
+
function createClient2(config) {
|
|
465
|
+
const chainPrefix = config.chain === "solana" ? "sol" : "evm";
|
|
466
|
+
const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}`;
|
|
467
|
+
return new import_sdk5.XacheClient({
|
|
468
|
+
apiUrl: config.apiUrl || "https://api.xache.xyz",
|
|
469
|
+
did,
|
|
470
|
+
privateKey: config.privateKey
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
function createReputationTool(config) {
|
|
474
|
+
const client = createClient2(config);
|
|
475
|
+
return new import_tools2.DynamicStructuredTool({
|
|
476
|
+
name: "xache_check_reputation",
|
|
477
|
+
description: "Check your current reputation score and status. Returns your score (0-1), level, and ERC-8004 on-chain status. Higher reputation means lower costs and more trust from other agents.",
|
|
478
|
+
schema: import_zod2.z.object({}),
|
|
479
|
+
func: async () => {
|
|
480
|
+
const result = await client.reputation.getReputation();
|
|
481
|
+
const score = (result.overall || 0) / 100;
|
|
482
|
+
const level = getLevel(score);
|
|
483
|
+
let output = `Reputation Score: ${score.toFixed(2)}/1.00 (${level})
|
|
484
|
+
`;
|
|
485
|
+
output += `Memory Quality: ${result.memoryQuality || 0}/100
|
|
486
|
+
`;
|
|
487
|
+
output += `Contribution Success: ${result.contribSuccess || 0}/100
|
|
488
|
+
`;
|
|
489
|
+
output += `Economic Value: ${result.economicValue || 0}/100
|
|
490
|
+
`;
|
|
491
|
+
try {
|
|
492
|
+
const erc8004Status = await client.reputation.getERC8004Status();
|
|
493
|
+
if (erc8004Status.enabled) {
|
|
494
|
+
output += `ERC-8004 Status: Enabled
|
|
495
|
+
`;
|
|
496
|
+
output += "Your reputation is verifiable on-chain!";
|
|
497
|
+
} else {
|
|
498
|
+
output += "ERC-8004 Status: Not enabled\n";
|
|
499
|
+
output += "Enable ERC-8004 to make your reputation portable and verifiable.";
|
|
500
|
+
}
|
|
501
|
+
} catch {
|
|
502
|
+
output += "ERC-8004 Status: Unknown";
|
|
503
|
+
}
|
|
504
|
+
return output;
|
|
505
|
+
}
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
var XacheReputationTool = class {
|
|
509
|
+
constructor(config) {
|
|
510
|
+
this.tool = createReputationTool(config);
|
|
511
|
+
}
|
|
512
|
+
asTool() {
|
|
513
|
+
return this.tool;
|
|
514
|
+
}
|
|
515
|
+
};
|
|
516
|
+
var XacheReputationChecker = class {
|
|
517
|
+
constructor(config) {
|
|
518
|
+
this.client = createClient2(config);
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Check an agent's reputation
|
|
522
|
+
*/
|
|
523
|
+
async check(agentDid) {
|
|
524
|
+
const result = await this.client.reputation.getReputation(agentDid);
|
|
525
|
+
const score = (result.overall || 0) / 100;
|
|
526
|
+
let erc8004Enabled = false;
|
|
527
|
+
let erc8004AgentId;
|
|
528
|
+
try {
|
|
529
|
+
const erc8004Status = await this.client.reputation.getERC8004Status();
|
|
530
|
+
erc8004Enabled = erc8004Status.enabled;
|
|
531
|
+
} catch {
|
|
532
|
+
}
|
|
533
|
+
return {
|
|
534
|
+
score,
|
|
535
|
+
level: getLevel(score),
|
|
536
|
+
totalContributions: 0,
|
|
537
|
+
// Not available in current API
|
|
538
|
+
totalPayments: 0,
|
|
539
|
+
// Not available in current API
|
|
540
|
+
erc8004Enabled,
|
|
541
|
+
erc8004AgentId
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Check if an agent meets minimum reputation threshold
|
|
546
|
+
*/
|
|
547
|
+
async meetsThreshold(agentDid, minScore) {
|
|
548
|
+
const result = await this.check(agentDid);
|
|
549
|
+
return result.score >= minScore;
|
|
550
|
+
}
|
|
551
|
+
};
|
|
552
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
553
|
+
0 && (module.exports = {
|
|
554
|
+
XacheChatMessageHistory,
|
|
555
|
+
XacheCollectiveContributeTool,
|
|
556
|
+
XacheCollectiveQueryTool,
|
|
557
|
+
XacheConversationBufferMemory,
|
|
558
|
+
XacheExtractor,
|
|
559
|
+
XacheMemory,
|
|
560
|
+
XacheReputationChecker,
|
|
561
|
+
XacheReputationTool,
|
|
562
|
+
XacheRetriever,
|
|
563
|
+
createCollectiveContributeTool,
|
|
564
|
+
createCollectiveQueryTool,
|
|
565
|
+
createReputationTool
|
|
566
|
+
});
|
|
567
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +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 } 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 /** Extraction mode: 'xache-managed' uses Xache's LLM, 'api-key' uses your own */\n mode?: 'xache-managed' | 'api-key';\n /** Your LLM API key (required if mode is 'api-key') */\n llmApiKey?: string;\n /** LLM provider for api-key mode */\n llmProvider?: 'anthropic' | 'openai';\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';\n private llmApiKey?: string;\n private llmProvider: 'anthropic' | 'openai';\n\n constructor(config: XacheExtractorConfig) {\n // Validate api-key mode requires llmApiKey\n const mode = config.mode || 'xache-managed';\n if (mode === 'api-key' && !config.llmApiKey) {\n throw new Error('llmApiKey is required when mode is \"api-key\"');\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 }\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 const llmConfig =\n this.mode === 'xache-managed'\n ? { type: 'xache-managed' as const, provider: 'anthropic' as const }\n : {\n type: 'api-key' as const,\n provider: this.llmProvider || ('anthropic' as const),\n apiKey: this.llmApiKey || '',\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,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