@xache/langchain 0.5.0 → 0.6.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # @xache/langchain
2
2
 
3
- LangChain.js integration for [Xache Protocol](https://xache.xyz) - verifiable AI agent memory with cryptographic receipts, collective intelligence, and portable ERC-8004 reputation.
3
+ LangChain.js integration for [Xache Protocol](https://xache.xyz) - verifiable AI agent memory with cryptographic receipts, collective intelligence, ephemeral working memory, knowledge graph, and portable ERC-8004 reputation.
4
4
 
5
5
  ## Installation
6
6
 
@@ -40,8 +40,8 @@ import { XacheMemory } from '@xache/langchain';
40
40
  const memory = new XacheMemory({
41
41
  walletAddress: '0xYourWallet',
42
42
  privateKey: '0xYourPrivateKey',
43
- apiUrl: 'https://api.xache.xyz', // optional
44
- chain: 'base', // or 'solana'
43
+ apiUrl: 'https://api.xache.xyz',
44
+ chain: 'base',
45
45
  });
46
46
  ```
47
47
 
@@ -56,7 +56,7 @@ import { RetrievalQAChain } from 'langchain/chains';
56
56
  const retriever = new XacheRetriever({
57
57
  walletAddress: '0x...',
58
58
  privateKey: '0x...',
59
- k: 5, // number of documents
59
+ k: 5,
60
60
  });
61
61
 
62
62
  const qa = RetrievalQAChain.fromLLM(llm, retriever);
@@ -64,15 +64,12 @@ const qa = RetrievalQAChain.fromLLM(llm, retriever);
64
64
 
65
65
  ### Collective Intelligence
66
66
 
67
- Query and contribute to shared knowledge:
68
-
69
67
  ```typescript
70
68
  import {
71
69
  createCollectiveContributeTool,
72
70
  createCollectiveQueryTool,
73
71
  } from '@xache/langchain';
74
72
 
75
- // Add to your agent's tools
76
73
  const contributeTool = createCollectiveContributeTool({
77
74
  walletAddress: '0x...',
78
75
  privateKey: '0x...',
@@ -82,34 +79,28 @@ const queryTool = createCollectiveQueryTool({
82
79
  walletAddress: '0x...',
83
80
  privateKey: '0x...',
84
81
  });
85
-
86
- const tools = [contributeTool, queryTool];
87
82
  ```
88
83
 
89
84
  ### Memory Extraction
90
85
 
91
- Auto-extract memories from conversations:
92
-
93
86
  ```typescript
94
87
  import { XacheExtractor } from '@xache/langchain';
95
88
 
96
89
  const extractor = new XacheExtractor({
97
90
  walletAddress: '0x...',
98
91
  privateKey: '0x...',
99
- mode: 'xache-managed', // or 'api-key' with your LLM key
92
+ mode: 'xache-managed',
100
93
  });
101
94
 
102
95
  const result = await extractor.extract(
103
96
  'User asked about quantum computing...',
104
97
  { autoStore: true }
105
98
  );
106
-
107
- console.log(`Extracted ${result.count} memories`);
108
99
  ```
109
100
 
110
101
  ### Knowledge Graph
111
102
 
112
- Build and query a privacy-preserving knowledge graph of entities and relationships:
103
+ Build and query a privacy-preserving knowledge graph:
113
104
 
114
105
  ```typescript
115
106
  import {
@@ -131,67 +122,81 @@ const config = {
131
122
  llmApiKey: 'sk-ant-...',
132
123
  };
133
124
 
134
- // Extract entities from text
135
125
  const extractTool = createGraphExtractTool(config);
136
-
137
- // Query graph around an entity
138
126
  const queryTool = createGraphQueryTool(config);
139
-
140
- // Ask natural language questions
141
127
  const askTool = createGraphAskTool(config);
142
-
143
- // Load the full graph
144
128
  const loadTool = createGraphLoadTool(config);
145
129
 
146
- // Add entities and relationships manually
147
- const addEntityTool = createGraphAddEntityTool(config);
148
- const addRelTool = createGraphAddRelationshipTool(config);
149
-
150
- // Merge duplicate entities
151
- const mergeTool = createGraphMergeEntitiesTool(config);
152
-
153
- // View entity version history
154
- const historyTool = createGraphEntityHistoryTool(config);
155
-
156
- // Use as a retriever for RAG
130
+ // Use graph as a retriever for RAG
157
131
  const graphRetriever = new XacheGraphRetriever({
158
132
  walletAddress: '0x...',
159
133
  privateKey: '0x...',
160
134
  k: 10,
161
135
  });
136
+ ```
137
+
138
+ ### Ephemeral Context (Working Memory)
162
139
 
163
- const docs = await graphRetriever.getRelevantDocuments('engineering team');
140
+ Short-lived scratch sessions for multi-turn workflows with 6 named slots (`conversation`, `facts`, `tasks`, `cache`, `scratch`, `handoff`):
141
+
142
+ ```typescript
143
+ import {
144
+ createEphemeralCreateSessionTool,
145
+ createEphemeralWriteSlotTool,
146
+ createEphemeralReadSlotTool,
147
+ createEphemeralPromoteTool,
148
+ createEphemeralStatusTool,
149
+ } from '@xache/langchain';
150
+
151
+ const config = {
152
+ walletAddress: '0x...',
153
+ privateKey: '0x...',
154
+ };
155
+
156
+ // Create tools for your agent
157
+ const createSessionTool = createEphemeralCreateSessionTool(config);
158
+ const writeSlotTool = createEphemeralWriteSlotTool(config);
159
+ const readSlotTool = createEphemeralReadSlotTool(config);
160
+ const promoteTool = createEphemeralPromoteTool(config);
161
+ const statusTool = createEphemeralStatusTool(config);
162
+
163
+ // Add to agent's toolkit
164
+ const tools = [createSessionTool, writeSlotTool, readSlotTool, promoteTool, statusTool];
164
165
  ```
165
166
 
166
- ### Reputation
167
+ Or use class-based wrappers:
167
168
 
168
- Check and verify agent reputation:
169
+ ```typescript
170
+ import {
171
+ XacheEphemeralCreateSessionTool,
172
+ XacheEphemeralWriteSlotTool,
173
+ XacheEphemeralReadSlotTool,
174
+ XacheEphemeralPromoteTool,
175
+ XacheEphemeralStatusTool,
176
+ } from '@xache/langchain';
177
+
178
+ const createSession = new XacheEphemeralCreateSessionTool(config);
179
+ const tool = createSession.asTool();
180
+ ```
181
+
182
+ ### Reputation
169
183
 
170
184
  ```typescript
171
185
  import { createReputationTool, XacheReputationChecker } from '@xache/langchain';
172
186
 
173
- // As a tool for your agent
174
187
  const repTool = createReputationTool({
175
188
  walletAddress: '0x...',
176
189
  privateKey: '0x...',
177
190
  });
178
191
 
179
- // Or check other agents
180
192
  const checker = new XacheReputationChecker({
181
193
  walletAddress: '0x...',
182
194
  privateKey: '0x...',
183
195
  });
184
-
185
- const otherRep = await checker.check('did:agent:evm:0xOtherAgent...');
186
- if (otherRep.score >= 0.5) {
187
- console.log('Agent is trustworthy');
188
- }
189
196
  ```
190
197
 
191
198
  ## Chat History
192
199
 
193
- For more control over message history:
194
-
195
200
  ```typescript
196
201
  import { XacheChatMessageHistory } from '@xache/langchain';
197
202
  import { BufferMemory } from 'langchain/memory';
@@ -209,19 +214,17 @@ const memory = new BufferMemory({ chatHistory: history });
209
214
 
210
215
  All operations use x402 micropayments (auto-handled):
211
216
 
212
- | Operation | Price |
213
- | -------------------- | ------ |
214
- | Memory Store | $0.002 |
215
- | Memory Retrieve | $0.003 |
216
- | Collective Contribute| $0.002 |
217
- | Collective Query | $0.011 |
217
+ | Operation | Price |
218
+ |-----------|-------|
219
+ | Memory Store | $0.002 |
220
+ | Memory Retrieve | $0.003 |
221
+ | Collective Contribute | $0.002 |
222
+ | Collective Query | $0.011 |
223
+ | Ephemeral Session | $0.005 |
224
+ | Ephemeral Promote | $0.05 |
218
225
  | Extraction (managed) | $0.011 |
219
- | Graph Operations | $0.002 |
220
- | Graph Ask (managed) | $0.011 |
221
-
222
- ## ERC-8004 Portable Reputation
223
-
224
- Xache supports [ERC-8004](https://eips.ethereum.org/EIPS/eip-8004) for portable, on-chain reputation. Enable it to make your agent's reputation verifiable across platforms.
226
+ | Graph Operations | $0.002 |
227
+ | Graph Ask (managed) | $0.011 |
225
228
 
226
229
  ## Resources
227
230
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xache/langchain",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "LangChain.js integration for Xache Protocol - verifiable AI agent memory",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",
@@ -51,7 +51,7 @@
51
51
  "langchain": ">=0.3.37"
52
52
  },
53
53
  "dependencies": {
54
- "@xache/sdk": "^5.8.0",
54
+ "@xache/sdk": "workspace:*",
55
55
  "zod": "^3.22.0"
56
56
  },
57
57
  "devDependencies": {
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Xache Ephemeral Context for LangChain.js
3
+ * Create, manage, and promote short-lived working memory sessions
4
+ */
5
+
6
+ import { DynamicStructuredTool } from '@langchain/core/tools';
7
+ import { z } from 'zod';
8
+ import {
9
+ XacheClient,
10
+ DID,
11
+ type XacheSigner,
12
+ type XacheWalletProvider,
13
+ } from '@xache/sdk';
14
+
15
+ // =============================================================================
16
+ // Configuration
17
+ // =============================================================================
18
+
19
+ export interface EphemeralToolConfig {
20
+ /** Wallet address for authentication */
21
+ walletAddress: string;
22
+ /** Private key for signing (optional if signer or walletProvider is provided) */
23
+ privateKey?: string;
24
+ /** External signer (alternative to privateKey) */
25
+ signer?: XacheSigner;
26
+ /** Wallet provider for lazy signer resolution */
27
+ walletProvider?: XacheWalletProvider;
28
+ /** Encryption key for use with external signers */
29
+ encryptionKey?: string;
30
+ /** API URL (defaults to https://api.xache.xyz) */
31
+ apiUrl?: string;
32
+ /** Chain: 'base' or 'solana' */
33
+ chain?: 'base' | 'solana';
34
+ }
35
+
36
+ function createClient(config: EphemeralToolConfig): XacheClient {
37
+ const chainPrefix = config.chain === 'solana' ? 'sol' : 'evm';
38
+ const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}` as DID;
39
+
40
+ return new XacheClient({
41
+ apiUrl: config.apiUrl || 'https://api.xache.xyz',
42
+ did,
43
+ privateKey: config.privateKey,
44
+ signer: config.signer,
45
+ walletProvider: config.walletProvider,
46
+ encryptionKey: config.encryptionKey,
47
+ });
48
+ }
49
+
50
+ // =============================================================================
51
+ // Factory Functions
52
+ // =============================================================================
53
+
54
+ /**
55
+ * Create a tool for creating an ephemeral working memory session.
56
+ */
57
+ export function createEphemeralCreateSessionTool(
58
+ config: EphemeralToolConfig
59
+ ): DynamicStructuredTool {
60
+ const client = createClient(config);
61
+
62
+ return new DynamicStructuredTool({
63
+ name: 'xache_ephemeral_create_session',
64
+ description:
65
+ 'Create a new ephemeral working memory session. ' +
66
+ 'Returns a session key for storing temporary data in slots.',
67
+ schema: z.object({
68
+ ttlSeconds: z.number().optional().describe('Session time-to-live in seconds (default: 3600)'),
69
+ maxWindows: z.number().optional().describe('Maximum renewal windows (default: 5)'),
70
+ }),
71
+ func: async ({ ttlSeconds, maxWindows }) => {
72
+ const session = await client.ephemeral.createSession({
73
+ ttlSeconds,
74
+ maxWindows,
75
+ });
76
+
77
+ return [
78
+ `Created ephemeral session.`,
79
+ `Session Key: ${session.sessionKey}`,
80
+ `Status: ${session.status}`,
81
+ `TTL: ${session.ttlSeconds}s`,
82
+ `Expires: ${session.expiresAt}`,
83
+ ].join('\n');
84
+ },
85
+ });
86
+ }
87
+
88
+ /**
89
+ * Create a tool for writing data to an ephemeral slot.
90
+ */
91
+ export function createEphemeralWriteSlotTool(
92
+ config: EphemeralToolConfig
93
+ ): DynamicStructuredTool {
94
+ const client = createClient(config);
95
+
96
+ return new DynamicStructuredTool({
97
+ name: 'xache_ephemeral_write_slot',
98
+ description:
99
+ 'Write data to an ephemeral session slot. ' +
100
+ 'Slots: conversation, facts, tasks, cache, scratch, handoff.',
101
+ schema: z.object({
102
+ sessionKey: z.string().describe('The ephemeral session key'),
103
+ slot: z.enum(['conversation', 'facts', 'tasks', 'cache', 'scratch', 'handoff']).describe('Slot name'),
104
+ data: z.record(z.string(), z.unknown()).describe('Data to write to the slot'),
105
+ }),
106
+ func: async ({ sessionKey, slot, data }) => {
107
+ await client.ephemeral.writeSlot(sessionKey, slot as any, data as Record<string, unknown>);
108
+ return `Wrote data to slot "${slot}" in session ${sessionKey.substring(0, 12)}...`;
109
+ },
110
+ });
111
+ }
112
+
113
+ /**
114
+ * Create a tool for reading data from an ephemeral slot.
115
+ */
116
+ export function createEphemeralReadSlotTool(
117
+ config: EphemeralToolConfig
118
+ ): DynamicStructuredTool {
119
+ const client = createClient(config);
120
+
121
+ return new DynamicStructuredTool({
122
+ name: 'xache_ephemeral_read_slot',
123
+ description:
124
+ 'Read data from an ephemeral session slot. ' +
125
+ 'Slots: conversation, facts, tasks, cache, scratch, handoff.',
126
+ schema: z.object({
127
+ sessionKey: z.string().describe('The ephemeral session key'),
128
+ slot: z.enum(['conversation', 'facts', 'tasks', 'cache', 'scratch', 'handoff']).describe('Slot name'),
129
+ }),
130
+ func: async ({ sessionKey, slot }) => {
131
+ const data = await client.ephemeral.readSlot(sessionKey, slot as any);
132
+ return JSON.stringify(data, null, 2);
133
+ },
134
+ });
135
+ }
136
+
137
+ /**
138
+ * Create a tool for promoting an ephemeral session to persistent memory.
139
+ */
140
+ export function createEphemeralPromoteTool(
141
+ config: EphemeralToolConfig
142
+ ): DynamicStructuredTool {
143
+ const client = createClient(config);
144
+
145
+ return new DynamicStructuredTool({
146
+ name: 'xache_ephemeral_promote',
147
+ description:
148
+ 'Promote an ephemeral session to persistent memory. ' +
149
+ 'Extracts valuable data from slots and stores as permanent memories.',
150
+ schema: z.object({
151
+ sessionKey: z.string().describe('The ephemeral session key to promote'),
152
+ }),
153
+ func: async ({ sessionKey }) => {
154
+ const result = await client.ephemeral.promoteSession(sessionKey);
155
+
156
+ let output = `Promoted session ${sessionKey.substring(0, 12)}...\n`;
157
+ output += `Memories created: ${result.memoriesCreated}\n`;
158
+ if (result.memoryIds.length > 0) {
159
+ output += `Memory IDs: ${result.memoryIds.join(', ')}\n`;
160
+ }
161
+ if (result.receiptId) {
162
+ output += `Receipt: ${result.receiptId}`;
163
+ }
164
+ return output;
165
+ },
166
+ });
167
+ }
168
+
169
+ /**
170
+ * Create a tool for getting ephemeral session status and details.
171
+ */
172
+ export function createEphemeralStatusTool(
173
+ config: EphemeralToolConfig
174
+ ): DynamicStructuredTool {
175
+ const client = createClient(config);
176
+
177
+ return new DynamicStructuredTool({
178
+ name: 'xache_ephemeral_status',
179
+ description:
180
+ 'Get the status and details of an ephemeral session. ' +
181
+ 'Shows active slots, size, TTL, and window information.',
182
+ schema: z.object({
183
+ sessionKey: z.string().describe('The ephemeral session key'),
184
+ }),
185
+ func: async ({ sessionKey }) => {
186
+ const session = await client.ephemeral.getSession(sessionKey);
187
+
188
+ if (!session) {
189
+ return `Session ${sessionKey.substring(0, 12)}... not found.`;
190
+ }
191
+
192
+ return [
193
+ `Session: ${session.sessionKey.substring(0, 12)}...`,
194
+ `Status: ${session.status}`,
195
+ `Window: ${session.window}/${session.maxWindows}`,
196
+ `TTL: ${session.ttlSeconds}s`,
197
+ `Expires: ${session.expiresAt}`,
198
+ `Active Slots: ${session.activeSlots.length > 0 ? session.activeSlots.join(', ') : 'none'}`,
199
+ `Total Size: ${session.totalSize} bytes`,
200
+ `Cumulative Cost: $${session.cumulativeCost.toFixed(4)}`,
201
+ ].join('\n');
202
+ },
203
+ });
204
+ }
205
+
206
+ // =============================================================================
207
+ // Class Wrappers
208
+ // =============================================================================
209
+
210
+ export class XacheEphemeralCreateSessionTool {
211
+ private tool: DynamicStructuredTool;
212
+
213
+ constructor(config: EphemeralToolConfig) {
214
+ this.tool = createEphemeralCreateSessionTool(config);
215
+ }
216
+
217
+ asTool(): DynamicStructuredTool {
218
+ return this.tool;
219
+ }
220
+ }
221
+
222
+ export class XacheEphemeralWriteSlotTool {
223
+ private tool: DynamicStructuredTool;
224
+
225
+ constructor(config: EphemeralToolConfig) {
226
+ this.tool = createEphemeralWriteSlotTool(config);
227
+ }
228
+
229
+ asTool(): DynamicStructuredTool {
230
+ return this.tool;
231
+ }
232
+ }
233
+
234
+ export class XacheEphemeralReadSlotTool {
235
+ private tool: DynamicStructuredTool;
236
+
237
+ constructor(config: EphemeralToolConfig) {
238
+ this.tool = createEphemeralReadSlotTool(config);
239
+ }
240
+
241
+ asTool(): DynamicStructuredTool {
242
+ return this.tool;
243
+ }
244
+ }
245
+
246
+ export class XacheEphemeralPromoteTool {
247
+ private tool: DynamicStructuredTool;
248
+
249
+ constructor(config: EphemeralToolConfig) {
250
+ this.tool = createEphemeralPromoteTool(config);
251
+ }
252
+
253
+ asTool(): DynamicStructuredTool {
254
+ return this.tool;
255
+ }
256
+ }
257
+
258
+ export class XacheEphemeralStatusTool {
259
+ private tool: DynamicStructuredTool;
260
+
261
+ constructor(config: EphemeralToolConfig) {
262
+ this.tool = createEphemeralStatusTool(config);
263
+ }
264
+
265
+ asTool(): DynamicStructuredTool {
266
+ return this.tool;
267
+ }
268
+ }
package/src/index.ts CHANGED
@@ -77,3 +77,18 @@ export {
77
77
  XacheGraphRetriever,
78
78
  } from './graph';
79
79
  export type { GraphToolConfig, XacheGraphRetrieverConfig } from './graph';
80
+
81
+ // Ephemeral Context
82
+ export {
83
+ createEphemeralCreateSessionTool,
84
+ createEphemeralWriteSlotTool,
85
+ createEphemeralReadSlotTool,
86
+ createEphemeralPromoteTool,
87
+ createEphemeralStatusTool,
88
+ XacheEphemeralCreateSessionTool,
89
+ XacheEphemeralWriteSlotTool,
90
+ XacheEphemeralReadSlotTool,
91
+ XacheEphemeralPromoteTool,
92
+ XacheEphemeralStatusTool,
93
+ } from './ephemeral';
94
+ export type { EphemeralToolConfig } from './ephemeral';