@maximem/synap-js-sdk 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/MIGRATING.md +147 -0
  2. package/README.md +95 -82
  3. package/bin/synap-js-sdk.js +45 -122
  4. package/dist/anticipation-cache-ARYEEKMU.cjs +10 -0
  5. package/dist/anticipation-cache-ARYEEKMU.cjs.map +1 -0
  6. package/dist/anticipation-cache-BMVF5sXb.d.cts +190 -0
  7. package/dist/anticipation-cache-BMVF5sXb.d.ts +190 -0
  8. package/dist/anticipation-cache-H7HEVWQC.js +10 -0
  9. package/dist/anticipation-cache-H7HEVWQC.js.map +1 -0
  10. package/dist/chunk-5SC3ELNK.js +856 -0
  11. package/dist/chunk-5SC3ELNK.js.map +1 -0
  12. package/dist/chunk-6LDUDKHS.js +832 -0
  13. package/dist/chunk-6LDUDKHS.js.map +1 -0
  14. package/dist/chunk-HR5Y3KXS.cjs +172 -0
  15. package/dist/chunk-HR5Y3KXS.cjs.map +1 -0
  16. package/dist/chunk-QBCVMPGK.js +28 -0
  17. package/dist/chunk-QBCVMPGK.js.map +1 -0
  18. package/dist/chunk-RB57I2IQ.cjs +832 -0
  19. package/dist/chunk-RB57I2IQ.cjs.map +1 -0
  20. package/dist/chunk-T3NZBIV2.js +172 -0
  21. package/dist/chunk-T3NZBIV2.js.map +1 -0
  22. package/dist/chunk-VXRCBMCY.cjs +856 -0
  23. package/dist/chunk-VXRCBMCY.cjs.map +1 -0
  24. package/dist/chunk-ZKOJDUN4.cjs +28 -0
  25. package/dist/chunk-ZKOJDUN4.cjs.map +1 -0
  26. package/dist/env-55ULHNJZ.cjs +11 -0
  27. package/dist/env-55ULHNJZ.cjs.map +1 -0
  28. package/dist/env-QCUKKW36.js +11 -0
  29. package/dist/env-QCUKKW36.js.map +1 -0
  30. package/dist/grpc/index.cjs +87 -0
  31. package/dist/grpc/index.cjs.map +1 -0
  32. package/dist/grpc/index.d.cts +162 -0
  33. package/dist/grpc/index.d.ts +162 -0
  34. package/dist/grpc/index.js +87 -0
  35. package/dist/grpc/index.js.map +1 -0
  36. package/dist/index.cjs +2702 -0
  37. package/dist/index.cjs.map +1 -0
  38. package/dist/index.d.cts +1491 -0
  39. package/dist/index.d.ts +1491 -0
  40. package/dist/index.js +2702 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/stream-client-ME5N5NK4.js +7 -0
  43. package/dist/stream-client-ME5N5NK4.js.map +1 -0
  44. package/dist/stream-client-ZN6ADZBR.cjs +7 -0
  45. package/dist/stream-client-ZN6ADZBR.cjs.map +1 -0
  46. package/package.json +68 -23
  47. package/.env.example +0 -39
  48. package/bridge/synap_bridge.py +0 -768
  49. package/src/bridge-manager.js +0 -262
  50. package/src/errors.js +0 -168
  51. package/src/index.js +0 -13
  52. package/src/runtime.js +0 -161
  53. package/src/setup-typescript.js +0 -161
  54. package/src/synap-client.js +0 -464
  55. package/types/index.d.ts +0 -475
@@ -1,161 +0,0 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const { runCommand } = require('./runtime');
4
-
5
- function detectPackageManager(projectDir, explicitPackageManager) {
6
- if (explicitPackageManager) return explicitPackageManager;
7
-
8
- if (fs.existsSync(path.join(projectDir, 'pnpm-lock.yaml'))) return 'pnpm';
9
- if (fs.existsSync(path.join(projectDir, 'yarn.lock'))) return 'yarn';
10
- if (fs.existsSync(path.join(projectDir, 'bun.lockb')) || fs.existsSync(path.join(projectDir, 'bun.lock'))) {
11
- return 'bun';
12
- }
13
-
14
- return 'npm';
15
- }
16
-
17
- function getInstallArgs(packageManager) {
18
- switch (packageManager) {
19
- case 'pnpm':
20
- return { command: 'pnpm', args: ['add', '-D', 'typescript', '@types/node'] };
21
- case 'yarn':
22
- return { command: 'yarn', args: ['add', '-D', 'typescript', '@types/node'] };
23
- case 'bun':
24
- return { command: 'bun', args: ['add', '-d', 'typescript', '@types/node'] };
25
- case 'npm':
26
- return { command: 'npm', args: ['install', '-D', 'typescript', '@types/node'] };
27
- default:
28
- throw new Error(`Unsupported package manager '${packageManager}'. Use npm, pnpm, yarn, or bun.`);
29
- }
30
- }
31
-
32
- function writeFileIfNeeded(filePath, contents, force) {
33
- if (fs.existsSync(filePath) && !force) {
34
- return false;
35
- }
36
-
37
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
38
- fs.writeFileSync(filePath, contents, 'utf8');
39
- return true;
40
- }
41
-
42
- function getTsconfigTemplate() {
43
- return `{
44
- "compilerOptions": {
45
- "target": "ES2020",
46
- "module": "CommonJS",
47
- "moduleResolution": "Node",
48
- "strict": true,
49
- "esModuleInterop": true,
50
- "forceConsistentCasingInFileNames": true,
51
- "skipLibCheck": true,
52
- "outDir": "dist"
53
- },
54
- "include": ["src/**/*.ts", "types/**/*.d.ts"]
55
- }
56
- `;
57
- }
58
-
59
- function getWrapperTemplate() {
60
- return `import {
61
- createClient,
62
- type SynapClient,
63
- type SynapClientOptions,
64
- type AddMemoryInput,
65
- type SearchMemoryInput,
66
- type GetMemoriesInput,
67
- type FetchUserContextInput,
68
- type FetchCustomerContextInput,
69
- type FetchClientContextInput,
70
- type GetContextForPromptInput,
71
- type DeleteMemoryInput,
72
- } from '@maximem/synap-js-sdk';
73
-
74
- export class SynapTsClient {
75
- private readonly client: SynapClient;
76
-
77
- constructor(options: SynapClientOptions = {}) {
78
- this.client = createClient(options);
79
- }
80
-
81
- init() {
82
- return this.client.init();
83
- }
84
-
85
- addMemory(input: AddMemoryInput) {
86
- return this.client.addMemory(input);
87
- }
88
-
89
- searchMemory(input: SearchMemoryInput) {
90
- return this.client.searchMemory(input);
91
- }
92
-
93
- getMemories(input: GetMemoriesInput) {
94
- return this.client.getMemories(input);
95
- }
96
-
97
- fetchUserContext(input: FetchUserContextInput) {
98
- return this.client.fetchUserContext(input);
99
- }
100
-
101
- fetchCustomerContext(input: FetchCustomerContextInput) {
102
- return this.client.fetchCustomerContext(input);
103
- }
104
-
105
- fetchClientContext(input?: FetchClientContextInput) {
106
- return this.client.fetchClientContext(input);
107
- }
108
-
109
- getContextForPrompt(input: GetContextForPromptInput) {
110
- return this.client.getContextForPrompt(input);
111
- }
112
-
113
- deleteMemory(input: DeleteMemoryInput) {
114
- return this.client.deleteMemory(input);
115
- }
116
-
117
- shutdown() {
118
- return this.client.shutdown();
119
- }
120
- }
121
-
122
- export const createTsClient = (options: SynapClientOptions = {}) => new SynapTsClient(options);
123
- `;
124
- }
125
-
126
- async function setupTypeScriptExtension(options = {}) {
127
- const projectDir = path.resolve(options.projectDir || process.cwd());
128
- const packageJsonPath = path.join(projectDir, 'package.json');
129
-
130
- if (!fs.existsSync(packageJsonPath)) {
131
- throw new Error(`No package.json found in ${projectDir}. Run setup-ts inside a Node project.`);
132
- }
133
-
134
- const packageManager = detectPackageManager(projectDir, options.packageManager);
135
- const tsconfigPath = path.resolve(projectDir, options.tsconfigPath || 'tsconfig.json');
136
- const wrapperPath = path.resolve(projectDir, options.wrapperPath || path.join('src', 'synap.ts'));
137
-
138
- if (!options.skipInstall) {
139
- const install = getInstallArgs(packageManager);
140
- await runCommand(install.command, install.args, { env: process.env, cwd: projectDir });
141
- }
142
-
143
- const tsconfigCreated = writeFileIfNeeded(tsconfigPath, getTsconfigTemplate(), options.force);
144
- const wrapperCreated = options.noWrapper
145
- ? false
146
- : writeFileIfNeeded(wrapperPath, getWrapperTemplate(), options.force);
147
-
148
- return {
149
- projectDir,
150
- packageManager,
151
- installedDevDependencies: !options.skipInstall,
152
- tsconfigPath,
153
- tsconfigCreated,
154
- wrapperPath: options.noWrapper ? null : wrapperPath,
155
- wrapperCreated,
156
- };
157
- }
158
-
159
- module.exports = {
160
- setupTypeScriptExtension,
161
- };
@@ -1,464 +0,0 @@
1
- const { BridgeManager } = require('./bridge-manager');
2
-
3
- function pickDefined(...values) {
4
- for (const value of values) {
5
- if (value !== undefined) return value;
6
- }
7
- return undefined;
8
- }
9
-
10
- function normalizeTemporalFields(item = {}) {
11
- return {
12
- eventDate: pickDefined(item.eventDate, item.event_date, null),
13
- validUntil: pickDefined(item.validUntil, item.valid_until, null),
14
- temporalCategory: pickDefined(item.temporalCategory, item.temporal_category, null),
15
- temporalConfidence: pickDefined(item.temporalConfidence, item.temporal_confidence, 0),
16
- };
17
- }
18
-
19
- function normalizeMemoryItem(item = {}) {
20
- return {
21
- id: item.id || '',
22
- memory: pickDefined(item.memory, item.content, ''),
23
- score: item.score,
24
- source: item.source,
25
- metadata: item.metadata || {},
26
- contextType: pickDefined(item.contextType, item.context_type),
27
- ...normalizeTemporalFields(item),
28
- };
29
- }
30
-
31
- function normalizeContextMetadata(metadata = {}) {
32
- return {
33
- correlationId: pickDefined(metadata.correlationId, metadata.correlation_id, ''),
34
- ttlSeconds: pickDefined(metadata.ttlSeconds, metadata.ttl_seconds, 0),
35
- source: metadata.source || 'unknown',
36
- retrievedAt: pickDefined(metadata.retrievedAt, metadata.retrieved_at, null),
37
- compactionApplied: pickDefined(metadata.compactionApplied, metadata.compaction_applied, null),
38
- };
39
- }
40
-
41
- function normalizeConversationContext(value) {
42
- if (!value) return null;
43
- return {
44
- summary: value.summary || null,
45
- currentState: pickDefined(value.currentState, value.current_state, {}),
46
- keyExtractions: pickDefined(value.keyExtractions, value.key_extractions, {}),
47
- recentTurns: pickDefined(value.recentTurns, value.recent_turns, []),
48
- compactionId: pickDefined(value.compactionId, value.compaction_id, null),
49
- compactedAt: pickDefined(value.compactedAt, value.compacted_at, null),
50
- conversationId: pickDefined(value.conversationId, value.conversation_id, null),
51
- };
52
- }
53
-
54
- function normalizeFact(item = {}) {
55
- return {
56
- id: item.id || '',
57
- content: item.content || '',
58
- confidence: pickDefined(item.confidence, 0),
59
- source: item.source || '',
60
- extractedAt: pickDefined(item.extractedAt, item.extracted_at, null),
61
- metadata: item.metadata || {},
62
- ...normalizeTemporalFields(item),
63
- };
64
- }
65
-
66
- function normalizePreference(item = {}) {
67
- return {
68
- id: item.id || '',
69
- category: item.category || '',
70
- content: item.content || '',
71
- strength: pickDefined(item.strength, item.confidence, 0),
72
- source: item.source || '',
73
- extractedAt: pickDefined(item.extractedAt, item.extracted_at, null),
74
- metadata: item.metadata || {},
75
- ...normalizeTemporalFields(item),
76
- };
77
- }
78
-
79
- function normalizeEpisode(item = {}) {
80
- return {
81
- id: item.id || '',
82
- summary: pickDefined(item.summary, item.content, ''),
83
- occurredAt: pickDefined(item.occurredAt, item.occurred_at, null),
84
- significance: pickDefined(item.significance, item.confidence, 0),
85
- participants: item.participants || [],
86
- metadata: item.metadata || {},
87
- ...normalizeTemporalFields(item),
88
- };
89
- }
90
-
91
- function normalizeEmotion(item = {}) {
92
- return {
93
- id: item.id || '',
94
- emotionType: pickDefined(item.emotionType, item.emotion_type, ''),
95
- intensity: pickDefined(item.intensity, item.confidence, 0),
96
- detectedAt: pickDefined(item.detectedAt, item.detected_at, null),
97
- context: item.context || '',
98
- metadata: item.metadata || {},
99
- ...normalizeTemporalFields(item),
100
- };
101
- }
102
-
103
- function normalizeTemporalEvent(item = {}) {
104
- return {
105
- id: item.id || '',
106
- content: item.content || '',
107
- eventDate: pickDefined(item.eventDate, item.event_date, null),
108
- validUntil: pickDefined(item.validUntil, item.valid_until, null),
109
- temporalCategory: pickDefined(item.temporalCategory, item.temporal_category, ''),
110
- temporalConfidence: pickDefined(item.temporalConfidence, item.temporal_confidence, 0),
111
- confidence: pickDefined(item.confidence, 0),
112
- source: item.source || '',
113
- extractedAt: pickDefined(item.extractedAt, item.extracted_at, null),
114
- metadata: item.metadata || {},
115
- };
116
- }
117
-
118
- function normalizeContextResponse(result = {}) {
119
- const context = result.context || result;
120
- return {
121
- facts: (context.facts || []).map(normalizeFact),
122
- preferences: (context.preferences || []).map(normalizePreference),
123
- episodes: (context.episodes || []).map(normalizeEpisode),
124
- emotions: (context.emotions || []).map(normalizeEmotion),
125
- temporalEvents: (pickDefined(context.temporalEvents, context.temporal_events, []) || []).map(normalizeTemporalEvent),
126
- conversationContext: normalizeConversationContext(
127
- pickDefined(context.conversationContext, context.conversation_context, null)
128
- ),
129
- metadata: normalizeContextMetadata(context.metadata || {}),
130
- rawResponse: pickDefined(context.rawResponse, context.raw_response, {}),
131
- bridgeTiming: result.bridgeTiming,
132
- };
133
- }
134
-
135
- function normalizeRecentMessage(item = {}) {
136
- return {
137
- role: item.role || 'user',
138
- content: item.content || '',
139
- timestamp: item.timestamp || null,
140
- messageId: pickDefined(item.messageId, item.message_id, ''),
141
- };
142
- }
143
-
144
- function normalizeContextForPromptResult(result = {}) {
145
- const payload = pickDefined(result.contextForPrompt, result.context_for_prompt, result);
146
- return {
147
- formattedContext: pickDefined(payload.formattedContext, payload.formatted_context, null),
148
- available: !!payload.available,
149
- isStale: !!pickDefined(payload.isStale, payload.is_stale, false),
150
- compressionRatio: pickDefined(payload.compressionRatio, payload.compression_ratio, null),
151
- validationScore: pickDefined(payload.validationScore, payload.validation_score, null),
152
- compactionAgeSeconds: pickDefined(payload.compactionAgeSeconds, payload.compaction_age_seconds, null),
153
- qualityWarning: !!pickDefined(payload.qualityWarning, payload.quality_warning, false),
154
- recentMessages: (pickDefined(payload.recentMessages, payload.recent_messages, []) || []).map(normalizeRecentMessage),
155
- recentMessageCount: pickDefined(payload.recentMessageCount, payload.recent_message_count, 0),
156
- compactedMessageCount: pickDefined(payload.compactedMessageCount, payload.compacted_message_count, 0),
157
- totalMessageCount: pickDefined(payload.totalMessageCount, payload.total_message_count, 0),
158
- bridgeTiming: result.bridgeTiming,
159
- };
160
- }
161
-
162
- function normalizeSearchMemoryResult(result = {}) {
163
- return {
164
- success: !!result.success,
165
- latencyMs: result.latencyMs || 0,
166
- results: (result.results || []).map(normalizeMemoryItem),
167
- resultsCount: pickDefined(result.resultsCount, result.results?.length, 0),
168
- rawResponse: result.rawResponse || {},
169
- source: result.source,
170
- bridgeTiming: result.bridgeTiming,
171
- };
172
- }
173
-
174
- function normalizeGetMemoriesResult(result = {}) {
175
- const memories = (result.memories || []).map(normalizeMemoryItem);
176
- return {
177
- success: !!result.success,
178
- latencyMs: result.latencyMs || 0,
179
- memories,
180
- totalCount: pickDefined(result.totalCount, result.memoriesCount, memories.length, 0),
181
- rawResponse: pickDefined(result.rawResponse, null),
182
- source: result.source,
183
- bridgeTiming: result.bridgeTiming,
184
- };
185
- }
186
-
187
- function normalizeDeleteMemoryResult(result = {}) {
188
- return {
189
- success: !!result.success,
190
- latencyMs: result.latencyMs || 0,
191
- deletedCount: pickDefined(result.deletedCount, result.rawResponse?.deleted, 0),
192
- rawResponse: pickDefined(result.rawResponse, null),
193
- note: result.note,
194
- bridgeTiming: result.bridgeTiming,
195
- };
196
- }
197
-
198
- class SynapClient {
199
- constructor(options = {}) {
200
- this.bridge = new BridgeManager(options);
201
- this.options = {
202
- ingestTimeoutMs: options.ingestTimeoutMs || 120_000,
203
- };
204
-
205
- this.#registerShutdownHooks();
206
- this.#installNamespacedApi();
207
- }
208
-
209
- async init() {
210
- await this.bridge.ensureStarted();
211
- }
212
-
213
- async addMemory({
214
- userId,
215
- customerId,
216
- conversationId,
217
- sessionId,
218
- messages,
219
- mode,
220
- documentType,
221
- documentId,
222
- documentCreatedAt,
223
- metadata,
224
- }) {
225
- this.#assert(userId, 'userId is required');
226
- this.#assert(customerId, 'customerId is required');
227
- this.#assert(Array.isArray(messages), 'messages must be an array');
228
-
229
- const params = { user_id: userId, messages };
230
- params.customer_id = customerId;
231
- if (conversationId !== undefined) params.conversation_id = conversationId;
232
- if (sessionId !== undefined) params.session_id = sessionId;
233
- if (mode !== undefined) params.mode = mode;
234
- if (documentType !== undefined) params.document_type = documentType;
235
- if (documentId !== undefined) params.document_id = documentId;
236
- if (documentCreatedAt !== undefined) params.document_created_at = documentCreatedAt;
237
- if (metadata !== undefined) params.metadata = metadata;
238
-
239
- return this.bridge.call('add_memory', params, this.options.ingestTimeoutMs);
240
- }
241
-
242
- async searchMemory({ userId, customerId, query, maxResults = 10, mode, conversationId, types }) {
243
- this.#assert(userId, 'userId is required');
244
- this.#assert(query, 'query is required');
245
- this.#assertArray(types, 'types must be an array when provided');
246
-
247
- const params = { user_id: userId, query, max_results: maxResults };
248
- if (customerId !== undefined) params.customer_id = customerId;
249
- if (mode !== undefined) params.mode = mode;
250
- if (conversationId !== undefined) params.conversation_id = conversationId;
251
- if (types !== undefined) params.types = types;
252
-
253
- return normalizeSearchMemoryResult(await this.bridge.call('search_memory', params));
254
- }
255
-
256
- async getMemories({ userId, customerId, mode, conversationId, maxResults, types }) {
257
- this.#assert(userId, 'userId is required');
258
- this.#assertArray(types, 'types must be an array when provided');
259
-
260
- const params = { user_id: userId };
261
- if (customerId !== undefined) params.customer_id = customerId;
262
- if (mode !== undefined) params.mode = mode;
263
- if (conversationId !== undefined) params.conversation_id = conversationId;
264
- if (maxResults !== undefined) params.max_results = maxResults;
265
- if (types !== undefined) params.types = types;
266
-
267
- return normalizeGetMemoriesResult(await this.bridge.call('get_memories', params));
268
- }
269
-
270
- async fetchUserContext({ userId, customerId, conversationId, searchQuery, maxResults = 10, types, mode }) {
271
- this.#assert(userId, 'userId is required');
272
- this.#assertArray(searchQuery, 'searchQuery must be an array when provided');
273
- this.#assertArray(types, 'types must be an array when provided');
274
-
275
- const params = { user_id: userId, max_results: maxResults };
276
- if (customerId !== undefined) params.customer_id = customerId;
277
- if (conversationId !== undefined) params.conversation_id = conversationId;
278
- if (searchQuery !== undefined) params.search_query = searchQuery;
279
- if (types !== undefined) params.types = types;
280
- if (mode !== undefined) params.mode = mode;
281
-
282
- return normalizeContextResponse(await this.bridge.call('fetch_user_context', params));
283
- }
284
-
285
- async fetchCustomerContext({ customerId, conversationId, searchQuery, maxResults = 10, types, mode }) {
286
- this.#assert(customerId, 'customerId is required');
287
- this.#assertArray(searchQuery, 'searchQuery must be an array when provided');
288
- this.#assertArray(types, 'types must be an array when provided');
289
-
290
- const params = { customer_id: customerId, max_results: maxResults };
291
- if (conversationId !== undefined) params.conversation_id = conversationId;
292
- if (searchQuery !== undefined) params.search_query = searchQuery;
293
- if (types !== undefined) params.types = types;
294
- if (mode !== undefined) params.mode = mode;
295
-
296
- return normalizeContextResponse(await this.bridge.call('fetch_customer_context', params));
297
- }
298
-
299
- async fetchClientContext({ conversationId, searchQuery, maxResults = 10, types, mode } = {}) {
300
- this.#assertArray(searchQuery, 'searchQuery must be an array when provided');
301
- this.#assertArray(types, 'types must be an array when provided');
302
-
303
- const params = { max_results: maxResults };
304
- if (conversationId !== undefined) params.conversation_id = conversationId;
305
- if (searchQuery !== undefined) params.search_query = searchQuery;
306
- if (types !== undefined) params.types = types;
307
- if (mode !== undefined) params.mode = mode;
308
-
309
- return normalizeContextResponse(await this.bridge.call('fetch_client_context', params));
310
- }
311
-
312
- async getContextForPrompt({ conversationId, style } = {}) {
313
- this.#assert(conversationId, 'conversationId is required');
314
-
315
- const params = { conversation_id: conversationId };
316
- if (style !== undefined) params.style = style;
317
-
318
- return normalizeContextForPromptResult(await this.bridge.call('get_context_for_prompt', params));
319
- }
320
-
321
- async deleteMemory({ userId, customerId, memoryId = null }) {
322
- this.#assert(userId, 'userId is required');
323
- if (memoryId == null) this.#assert(customerId, 'customerId is required when memoryId is not provided');
324
-
325
- const params = { user_id: userId, memory_id: memoryId };
326
- if (customerId !== undefined) params.customer_id = customerId;
327
-
328
- return normalizeDeleteMemoryResult(await this.bridge.call('delete_memory', params));
329
- }
330
-
331
- async shutdown() {
332
- await this.bridge.shutdown();
333
- }
334
-
335
- #assert(value, message) {
336
- if (!value) throw new Error(message);
337
- }
338
-
339
- #assertArray(value, message) {
340
- if (value !== undefined && !Array.isArray(value)) throw new Error(message);
341
- }
342
-
343
- #registerShutdownHooks() {
344
- const close = async () => {
345
- try {
346
- await this.shutdown();
347
- } catch (_) {
348
- // Best-effort shutdown.
349
- }
350
- };
351
-
352
- process.once('beforeExit', close);
353
- process.once('SIGINT', async () => {
354
- await close();
355
- process.exit(0);
356
- });
357
- process.once('SIGTERM', async () => {
358
- await close();
359
- process.exit(0);
360
- });
361
- }
362
-
363
- #installNamespacedApi() {
364
- const buildParams = (args = {}) => {
365
- const params = {};
366
- const conv = pickDefined(args.conversation_id, args.conversationId);
367
- const sq = pickDefined(args.search_query, args.searchQuery);
368
- const mr = pickDefined(args.max_results, args.maxResults);
369
- if (conv !== undefined && conv !== null) params.conversation_id = conv;
370
- if (sq !== undefined && sq !== null) params.search_query = sq;
371
- if (mr !== undefined) params.max_results = mr;
372
- if (args.types !== undefined) params.types = args.types;
373
- if (args.mode !== undefined) params.mode = args.mode;
374
- return params;
375
- };
376
- const fetch = async (args = {}) => {
377
- const userId = pickDefined(args.user_id, args.userId);
378
- const customerId = pickDefined(args.customer_id, args.customerId);
379
- const params = buildParams(args);
380
- let command;
381
- if (userId !== undefined && userId !== null) {
382
- command = 'fetch_user_context';
383
- params.user_id = userId;
384
- if (customerId !== undefined && customerId !== null) params.customer_id = customerId;
385
- } else if (customerId !== undefined && customerId !== null) {
386
- command = 'fetch_customer_context';
387
- params.customer_id = customerId;
388
- } else {
389
- command = 'fetch_client_context';
390
- }
391
- const result = await this.bridge.call(command, params);
392
- return result.context || {};
393
- };
394
- const fetchScope = (command, idKeys) => async (args = {}) => {
395
- const params = buildParams(args);
396
- if (idKeys.includes('user_id')) {
397
- const userId = pickDefined(args.user_id, args.userId);
398
- if (userId !== undefined && userId !== null) params.user_id = userId;
399
- }
400
- if (idKeys.includes('customer_id')) {
401
- const customerId = pickDefined(args.customer_id, args.customerId);
402
- if (customerId !== undefined && customerId !== null) params.customer_id = customerId;
403
- }
404
- const result = await this.bridge.call(command, params);
405
- return result.context || {};
406
- };
407
- this.fetch = fetch;
408
- this.conversation = {
409
- record_message: async (args = {}) => {
410
- const conversationId = pickDefined(args.conversation_id, args.conversationId);
411
- const userId = pickDefined(args.user_id, args.userId);
412
- const customerId = pickDefined(args.customer_id, args.customerId);
413
- this.#assert(conversationId, 'conversation_id is required');
414
- this.#assert(userId, 'user_id is required');
415
- this.#assert(customerId, 'customer_id is required');
416
- const params = {
417
- conversation_id: conversationId, role: args.role, content: args.content,
418
- user_id: userId, customer_id: customerId,
419
- };
420
- const sessionId = pickDefined(args.session_id, args.sessionId);
421
- if (sessionId !== undefined) params.session_id = sessionId;
422
- if (args.metadata !== undefined) params.metadata = args.metadata;
423
- const result = await this.bridge.call('record_message', params);
424
- return pickDefined(result.result, result);
425
- },
426
- context: {
427
- get_context_for_prompt: async (args = {}) => {
428
- const conversationId = pickDefined(args.conversation_id, args.conversationId);
429
- this.#assert(conversationId, 'conversation_id is required');
430
- const params = { conversation_id: conversationId };
431
- if (args.style !== undefined) params.style = args.style;
432
- const result = await this.bridge.call('get_context_for_prompt', params);
433
- return pickDefined(result.context_for_prompt, result.contextForPrompt, {});
434
- },
435
- fetch,
436
- },
437
- };
438
- this.memories = {
439
- create: async (args = {}) => {
440
- this.#assert(args.document, 'document is required');
441
- const params = { document: args.document };
442
- const userId = pickDefined(args.user_id, args.userId);
443
- const customerId = pickDefined(args.customer_id, args.customerId);
444
- const documentType = pickDefined(args.document_type, args.documentType);
445
- const documentId = pickDefined(args.document_id, args.documentId);
446
- const documentCreatedAt = pickDefined(args.document_created_at, args.documentCreatedAt);
447
- if (userId !== undefined) params.user_id = userId;
448
- if (customerId !== undefined) params.customer_id = customerId;
449
- if (documentType !== undefined) params.document_type = documentType;
450
- if (documentId !== undefined) params.document_id = documentId;
451
- if (documentCreatedAt !== undefined) params.document_created_at = documentCreatedAt;
452
- if (args.mode !== undefined) params.mode = args.mode;
453
- if (args.metadata !== undefined) params.metadata = args.metadata;
454
- const result = await this.bridge.call('create_memory', params, this.options.ingestTimeoutMs);
455
- return pickDefined(result.result, result);
456
- },
457
- };
458
- this.user = { context: { fetch: fetchScope('fetch_user_context', ['user_id', 'customer_id']) } };
459
- this.customer = { context: { fetch: fetchScope('fetch_customer_context', ['customer_id']) } };
460
- this.client = { context: { fetch: fetchScope('fetch_client_context', []) } };
461
- }
462
- }
463
-
464
- module.exports = { SynapClient };