dsh-mnemon 0.4.7 → 0.5.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.
Files changed (136) hide show
  1. package/README.md +10 -20
  2. package/README.zh-CN.md +10 -20
  3. package/SECURITY.md +8 -8
  4. package/cordis.patch.yml +42 -0
  5. package/lib/client.js +2360 -6843
  6. package/lib/contracts.js +16 -17
  7. package/lib/core.js +11 -0
  8. package/lib/definitions-j0FLgE0-.js +251 -0
  9. package/lib/extension-sdk.js +93 -229
  10. package/lib/index.js +3730 -6330
  11. package/lib/runtime-AtIOTeP1.js +1316 -0
  12. package/lib/storage-lock-Bqrhkyag.js +20 -0
  13. package/lib/testing.js +231 -0
  14. package/lib/types/src/client/extension-sdk.d.ts +10 -0
  15. package/lib/types/src/client/index.d.ts +1 -0
  16. package/lib/types/src/client/locales.d.ts +84 -0
  17. package/lib/types/src/client/page-client.d.ts +15 -0
  18. package/lib/types/src/client/page-kit.d.ts +40 -0
  19. package/lib/types/src/client/source-contracts.d.ts +46 -0
  20. package/lib/types/src/client/source-pages.d.ts +83 -0
  21. package/lib/types/src/core/contracts/index.d.ts +40 -0
  22. package/lib/types/src/core/contracts/plugin.d.ts +32 -0
  23. package/lib/types/src/core/contracts/view.d.ts +416 -0
  24. package/lib/types/src/core/definitions.d.ts +16 -0
  25. package/lib/types/src/core/plugin.d.ts +6 -0
  26. package/lib/types/src/{config-values.d.ts → host/config-values.d.ts} +7 -7
  27. package/lib/types/src/{config.d.ts → host/config.d.ts} +4 -1
  28. package/lib/types/src/{shared → host}/display-mode.d.ts +1 -1
  29. package/lib/types/src/host/plugin.d.ts +8 -0
  30. package/lib/types/src/host/protocol.d.ts +549 -0
  31. package/lib/types/src/host/view-protocol.d.ts +123 -0
  32. package/lib/types/src/index.d.ts +2 -21
  33. package/lib/types/src/sdk/index.d.ts +9 -0
  34. package/lib/types/src/sdk/input.d.ts +11 -0
  35. package/lib/types/src/sdk/install.d.ts +7 -0
  36. package/lib/types/src/sdk/service.d.ts +31 -0
  37. package/lib/types/src/sdk/storage-lock.d.ts +6 -0
  38. package/lib/types/src/sdk/strategy-configuration.d.ts +31 -0
  39. package/lib/types/src/sdk/testing.d.ts +70 -0
  40. package/package.json +46 -35
  41. package/lib/kernel.js +0 -1173
  42. package/lib/layers/documents.js +0 -31
  43. package/lib/layers/memory-spaces.js +0 -34
  44. package/lib/layers/runtime.js +0 -27
  45. package/lib/provider-sdk.js +0 -2
  46. package/lib/registry-B9SdBRLo.js +0 -2423
  47. package/lib/strategy-default-three-tier.js +0 -99
  48. package/lib/strategy-sdk.js +0 -56
  49. package/lib/types/packages/contracts/src/index.d.ts +0 -221
  50. package/lib/types/packages/extension-sdk/src/index.d.ts +0 -54
  51. package/lib/types/packages/kernel/src/access.d.ts +0 -14
  52. package/lib/types/packages/kernel/src/catalog.d.ts +0 -42
  53. package/lib/types/packages/kernel/src/index.d.ts +0 -5
  54. package/lib/types/packages/kernel/src/kernel.d.ts +0 -46
  55. package/lib/types/packages/kernel/src/topology.d.ts +0 -25
  56. package/lib/types/packages/kernel/src/view.d.ts +0 -89
  57. package/lib/types/packages/layer-documents/src/index.d.ts +0 -4
  58. package/lib/types/packages/layer-memory-spaces/src/index.d.ts +0 -4
  59. package/lib/types/packages/layer-runtime/src/index.d.ts +0 -4
  60. package/lib/types/packages/provider-sdk/src/index.d.ts +0 -19
  61. package/lib/types/packages/strategy-default-three-tier/src/index.d.ts +0 -7
  62. package/lib/types/packages/strategy-sdk/src/index.d.ts +0 -35
  63. package/lib/types/src/activity.d.ts +0 -16
  64. package/lib/types/src/agent-memory-turn.d.ts +0 -42
  65. package/lib/types/src/channels.d.ts +0 -1
  66. package/lib/types/src/client/GlobalLocationSetting.d.ts +0 -19
  67. package/lib/types/src/client/MnemonPackSection.d.ts +0 -13
  68. package/lib/types/src/client/MnemonSaveAction.d.ts +0 -13
  69. package/lib/types/src/client/MnemonSettingsCard.d.ts +0 -16
  70. package/lib/types/src/client/MnemonTurnTail.d.ts +0 -21
  71. package/lib/types/src/client/MnemonView.d.ts +0 -26
  72. package/lib/types/src/client/ProviderIcon.d.ts +0 -8
  73. package/lib/types/src/client/ProviderSettingsSection.d.ts +0 -16
  74. package/lib/types/src/client/anchor.d.ts +0 -27
  75. package/lib/types/src/client/api.d.ts +0 -83
  76. package/lib/types/src/client/better-sidebar.d.ts +0 -13
  77. package/lib/types/src/client/dsh-compat.d.ts +0 -51
  78. package/lib/types/src/client/settings.d.ts +0 -23
  79. package/lib/types/src/client/sidebar-entry.d.ts +0 -5
  80. package/lib/types/src/client/subagent-token-usage.d.ts +0 -23
  81. package/lib/types/src/client/workspace-controller.d.ts +0 -14
  82. package/lib/types/src/client/workspace-mount.d.ts +0 -20
  83. package/lib/types/src/commands.d.ts +0 -13
  84. package/lib/types/src/contracts.d.ts +0 -316
  85. package/lib/types/src/documents.d.ts +0 -77
  86. package/lib/types/src/git-branch.d.ts +0 -6
  87. package/lib/types/src/guidance.d.ts +0 -29
  88. package/lib/types/src/lifecycle.d.ts +0 -80
  89. package/lib/types/src/live-runtime.d.ts +0 -92
  90. package/lib/types/src/memory-bodies.d.ts +0 -57
  91. package/lib/types/src/memory-receipts.d.ts +0 -21
  92. package/lib/types/src/memory-system/access.d.ts +0 -2
  93. package/lib/types/src/memory-system/catalog.d.ts +0 -2
  94. package/lib/types/src/memory-system/contracts.d.ts +0 -2
  95. package/lib/types/src/memory-system/defaults.d.ts +0 -6
  96. package/lib/types/src/memory-system/index.d.ts +0 -7
  97. package/lib/types/src/memory-system/kernel.d.ts +0 -2
  98. package/lib/types/src/memory-system/topology.d.ts +0 -2
  99. package/lib/types/src/memory-system/view.d.ts +0 -2
  100. package/lib/types/src/memory-view.d.ts +0 -21
  101. package/lib/types/src/pack.d.ts +0 -29
  102. package/lib/types/src/process.d.ts +0 -16
  103. package/lib/types/src/provider-placement.d.ts +0 -26
  104. package/lib/types/src/provider-sdk.d.ts +0 -4
  105. package/lib/types/src/providers/byterover.d.ts +0 -32
  106. package/lib/types/src/providers/catalog.d.ts +0 -23
  107. package/lib/types/src/providers/hindsight.d.ts +0 -20
  108. package/lib/types/src/providers/holographic.d.ts +0 -23
  109. package/lib/types/src/providers/honcho.d.ts +0 -18
  110. package/lib/types/src/providers/http.d.ts +0 -32
  111. package/lib/types/src/providers/mem0.d.ts +0 -18
  112. package/lib/types/src/providers/memory-system.d.ts +0 -6
  113. package/lib/types/src/providers/openviking.d.ts +0 -32
  114. package/lib/types/src/providers/provider.d.ts +0 -46
  115. package/lib/types/src/providers/registry.d.ts +0 -23
  116. package/lib/types/src/providers/retaindb.d.ts +0 -17
  117. package/lib/types/src/providers/supermemory.d.ts +0 -17
  118. package/lib/types/src/recall-quality/contracts.d.ts +0 -32
  119. package/lib/types/src/recall-quality/engine.d.ts +0 -13
  120. package/lib/types/src/recall-quality/index.d.ts +0 -4
  121. package/lib/types/src/recall-quality/policies.d.ts +0 -5
  122. package/lib/types/src/recall-quality/registry.d.ts +0 -10
  123. package/lib/types/src/review-activity.d.ts +0 -19
  124. package/lib/types/src/rpc.d.ts +0 -22
  125. package/lib/types/src/runner.d.ts +0 -41
  126. package/lib/types/src/runtime-memory.d.ts +0 -90
  127. package/lib/types/src/search-tokens.d.ts +0 -5
  128. package/lib/types/src/service.d.ts +0 -113
  129. package/lib/types/src/session-events.d.ts +0 -8
  130. package/lib/types/src/settings.d.ts +0 -6
  131. package/lib/types/src/shared/contracts.d.ts +0 -1008
  132. package/lib/types/src/storage-scope.d.ts +0 -12
  133. package/lib/types/src/subagent-token-usage.d.ts +0 -53
  134. package/lib/types/src/subagent.d.ts +0 -124
  135. package/lib/types/src/tools.d.ts +0 -10
  136. package/lib/types/src/version-updates.d.ts +0 -37
@@ -1,2423 +0,0 @@
1
- import { basename, dirname, isAbsolute, join, resolve } from "node:path";
2
- import { createHash, randomUUID } from "node:crypto";
3
- import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
- import { spawn } from "node:child_process";
5
- //#region src/process.ts
6
- const DEFAULT_MAX_OUTPUT_BYTES = 2097152;
7
- /** Spawn without a shell, with bounded output and cooperative cancellation. */
8
- const runProcess = (command, args, options) => new Promise((resolve, reject) => {
9
- const label = options.label ?? "mnemon";
10
- const child = spawn(command, [...args], {
11
- stdio: [
12
- "ignore",
13
- "pipe",
14
- "pipe"
15
- ],
16
- shell: false,
17
- windowsHide: true,
18
- ...options.cwd === void 0 ? {} : { cwd: options.cwd },
19
- ...options.env === void 0 ? {} : { env: options.env }
20
- });
21
- const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
22
- let stdout = "";
23
- let stderr = "";
24
- let outputBytes = 0;
25
- let settled = false;
26
- let killTimer;
27
- const stop = () => {
28
- if (child.exitCode !== null || child.signalCode !== null) return;
29
- child.kill("SIGTERM");
30
- killTimer = setTimeout(() => {
31
- if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
32
- }, 1500);
33
- };
34
- const finish = (error, result) => {
35
- if (settled) return;
36
- settled = true;
37
- clearTimeout(timeout);
38
- if (killTimer !== void 0) clearTimeout(killTimer);
39
- options.signal?.removeEventListener("abort", abort);
40
- if (error === null) resolve(result);
41
- else reject(error);
42
- };
43
- const abort = () => {
44
- stop();
45
- finish(/* @__PURE__ */ new Error(`${label} command aborted: ${String(options.signal?.reason ?? "cancelled")}`));
46
- };
47
- const append = (target, chunk) => {
48
- outputBytes += chunk.byteLength;
49
- if (outputBytes > maxOutputBytes) {
50
- stop();
51
- finish(/* @__PURE__ */ new Error(`${label} output exceeded ${maxOutputBytes} bytes`));
52
- return;
53
- }
54
- if (target === "stdout") stdout += chunk.toString("utf8");
55
- else stderr += chunk.toString("utf8");
56
- };
57
- child.stdout.on("data", (chunk) => {
58
- append("stdout", chunk);
59
- });
60
- child.stderr.on("data", (chunk) => {
61
- append("stderr", chunk);
62
- });
63
- child.on("error", (error) => {
64
- finish(/* @__PURE__ */ new Error(`failed to launch ${label} (${JSON.stringify(command)}): ${error.message}`));
65
- });
66
- child.on("close", (exitCode) => {
67
- finish(null, {
68
- stdout,
69
- stderr,
70
- exitCode
71
- });
72
- });
73
- const timeout = setTimeout(() => {
74
- stop();
75
- finish(/* @__PURE__ */ new Error(`${label} did not respond within ${options.timeoutMs}ms`));
76
- }, options.timeoutMs);
77
- if (options.signal?.aborted === true) abort();
78
- else options.signal?.addEventListener("abort", abort, { once: true });
79
- });
80
- //#endregion
81
- //#region src/providers/catalog.ts
82
- const NATIVE_CAPABILITIES = {
83
- search: true,
84
- browse: true,
85
- graph: true,
86
- entities: true,
87
- related: true,
88
- remember: true,
89
- link: true,
90
- forget: true,
91
- writeMode: "exact",
92
- deletionMode: "soft"
93
- };
94
- const REMOTE_EXACT_CAPABILITIES = {
95
- search: true,
96
- browse: true,
97
- graph: false,
98
- entities: false,
99
- related: false,
100
- remember: true,
101
- link: false,
102
- forget: true,
103
- writeMode: "exact",
104
- deletionMode: "hard"
105
- };
106
- const field = (value) => value;
107
- const MEMORY_PROVIDER_IDS = [
108
- "mnemon-native",
109
- "openviking",
110
- "honcho",
111
- "mem0",
112
- "hindsight",
113
- "holographic",
114
- "retaindb",
115
- "byterover",
116
- "supermemory"
117
- ];
118
- const MEMORY_PROVIDER_ID_SET = new Set(MEMORY_PROVIDER_IDS);
119
- const MEMORY_PROVIDER_CATALOG = [
120
- {
121
- id: "mnemon-native",
122
- label: "mnemon",
123
- kind: "local",
124
- workspaceBinding: "automatic",
125
- summary: "Official local-first memory with exact writes, typed graph relations, and soft deletion.",
126
- origin: "native",
127
- capabilities: NATIVE_CAPABILITIES,
128
- fields: []
129
- },
130
- {
131
- id: "openviking",
132
- label: "OpenViking",
133
- kind: "remote",
134
- workspaceBinding: "provider-global",
135
- summary: "Filesystem-shaped shared memory with tiered reads and automatic semantic extraction.",
136
- origin: "third-party",
137
- capabilities: {
138
- ...REMOTE_EXACT_CAPABILITIES,
139
- writeMode: "async-extracting"
140
- },
141
- fields: [
142
- field({
143
- key: "endpoint",
144
- label: "Endpoint",
145
- scope: "service",
146
- input: "url",
147
- required: true,
148
- defaultValue: "http://127.0.0.1:1933",
149
- placeholder: "http://127.0.0.1:1933"
150
- }),
151
- field({
152
- key: "targetUri",
153
- label: "Memory URI",
154
- scope: "memory",
155
- input: "text",
156
- required: true,
157
- defaultValue: "viking://user/memories",
158
- placeholder: "viking://user/memories"
159
- }),
160
- field({
161
- key: "apiKey",
162
- label: "API key",
163
- scope: "service",
164
- input: "secret",
165
- required: false
166
- }),
167
- field({
168
- key: "account",
169
- label: "Account",
170
- scope: "service",
171
- input: "text",
172
- required: false
173
- }),
174
- field({
175
- key: "user",
176
- label: "User",
177
- scope: "memory",
178
- input: "text",
179
- required: false
180
- }),
181
- field({
182
- key: "actorPeerId",
183
- label: "Agent peer",
184
- scope: "memory",
185
- input: "text",
186
- required: false,
187
- defaultValue: "dsh"
188
- })
189
- ]
190
- },
191
- {
192
- id: "honcho",
193
- label: "Honcho",
194
- kind: "remote",
195
- workspaceBinding: "provider-global",
196
- summary: "Cross-session user modelling, peer profiles, dialectic reasoning, and persistent conclusions.",
197
- origin: "third-party",
198
- capabilities: REMOTE_EXACT_CAPABILITIES,
199
- fields: [
200
- field({
201
- key: "endpoint",
202
- label: "Endpoint",
203
- scope: "service",
204
- input: "url",
205
- required: true,
206
- defaultValue: "https://api.honcho.dev"
207
- }),
208
- field({
209
- key: "apiKey",
210
- label: "API key",
211
- scope: "service",
212
- input: "secret",
213
- required: false
214
- }),
215
- field({
216
- key: "workspace",
217
- label: "Workspace",
218
- scope: "memory",
219
- input: "text",
220
- required: true,
221
- defaultValue: "dsh"
222
- }),
223
- field({
224
- key: "userId",
225
- label: "User peer",
226
- scope: "memory",
227
- input: "text",
228
- required: true,
229
- defaultValue: "dsh-user"
230
- }),
231
- field({
232
- key: "agentId",
233
- label: "Agent peer",
234
- scope: "memory",
235
- input: "text",
236
- required: true,
237
- defaultValue: "dsh"
238
- })
239
- ]
240
- },
241
- {
242
- id: "mem0",
243
- label: "Mem0",
244
- kind: "remote",
245
- workspaceBinding: "provider-global",
246
- summary: "Automatic fact extraction, semantic retrieval, reranking, and deduplication.",
247
- origin: "third-party",
248
- capabilities: {
249
- ...REMOTE_EXACT_CAPABILITIES,
250
- writeMode: "async-extracting"
251
- },
252
- fields: [
253
- field({
254
- key: "endpoint",
255
- label: "Endpoint",
256
- scope: "service",
257
- input: "url",
258
- required: true,
259
- defaultValue: "https://api.mem0.ai"
260
- }),
261
- field({
262
- key: "apiKey",
263
- label: "API key",
264
- scope: "service",
265
- input: "secret",
266
- required: false
267
- }),
268
- field({
269
- key: "mode",
270
- label: "Mode",
271
- scope: "service",
272
- input: "select",
273
- required: true,
274
- defaultValue: "platform",
275
- options: [{
276
- value: "platform",
277
- label: "Mem0 Platform"
278
- }, {
279
- value: "self-hosted",
280
- label: "Self-hosted server"
281
- }]
282
- }),
283
- field({
284
- key: "userId",
285
- label: "User ID",
286
- scope: "memory",
287
- input: "text",
288
- required: true,
289
- defaultValue: "dsh-user"
290
- }),
291
- field({
292
- key: "agentId",
293
- label: "Agent ID",
294
- scope: "memory",
295
- input: "text",
296
- required: true,
297
- defaultValue: "dsh"
298
- }),
299
- field({
300
- key: "rerank",
301
- label: "Rerank search results",
302
- scope: "memory",
303
- input: "boolean",
304
- required: false,
305
- defaultValue: false
306
- })
307
- ]
308
- },
309
- {
310
- id: "hindsight",
311
- label: "Hindsight",
312
- kind: "remote",
313
- workspaceBinding: "provider-global",
314
- summary: "Knowledge-graph memory with entity resolution, observations, multi-strategy recall, and reflection.",
315
- origin: "third-party",
316
- capabilities: {
317
- ...REMOTE_EXACT_CAPABILITIES,
318
- graph: true,
319
- entities: true,
320
- related: true,
321
- writeMode: "async-extracting",
322
- deletionMode: "soft"
323
- },
324
- fields: [
325
- field({
326
- key: "endpoint",
327
- label: "Endpoint",
328
- scope: "service",
329
- input: "url",
330
- required: true,
331
- defaultValue: "https://api.hindsight.vectorize.io"
332
- }),
333
- field({
334
- key: "apiKey",
335
- label: "API key",
336
- scope: "service",
337
- input: "secret",
338
- required: false
339
- }),
340
- field({
341
- key: "bankId",
342
- label: "Memory bank",
343
- scope: "memory",
344
- input: "text",
345
- required: true,
346
- defaultValue: "dsh"
347
- }),
348
- field({
349
- key: "budget",
350
- label: "Recall budget",
351
- scope: "memory",
352
- input: "select",
353
- required: true,
354
- defaultValue: "mid",
355
- options: [
356
- {
357
- value: "low",
358
- label: "Low"
359
- },
360
- {
361
- value: "mid",
362
- label: "Medium"
363
- },
364
- {
365
- value: "high",
366
- label: "High"
367
- }
368
- ]
369
- })
370
- ]
371
- },
372
- {
373
- id: "holographic",
374
- label: "Holographic",
375
- kind: "local",
376
- workspaceBinding: "optional-override",
377
- summary: "Local structured fact memory with trust scoring, entity resolution, and compositional retrieval.",
378
- origin: "third-party",
379
- capabilities: {
380
- ...NATIVE_CAPABILITIES,
381
- link: false,
382
- deletionMode: "hard"
383
- },
384
- fields: [
385
- field({
386
- key: "dataPath",
387
- label: "Fact store path",
388
- scope: "service",
389
- role: "global-location",
390
- input: "path",
391
- required: false
392
- }),
393
- field({
394
- key: "defaultTrust",
395
- label: "Default trust",
396
- scope: "memory",
397
- input: "number",
398
- required: true,
399
- defaultValue: .5
400
- }),
401
- field({
402
- key: "minTrust",
403
- label: "Minimum recall trust",
404
- scope: "memory",
405
- input: "number",
406
- required: true,
407
- defaultValue: .3
408
- })
409
- ]
410
- },
411
- {
412
- id: "retaindb",
413
- label: "RetainDB",
414
- kind: "remote",
415
- workspaceBinding: "provider-global",
416
- summary: "Cloud memory with hybrid vector/BM25 retrieval, profiles, and typed durable facts.",
417
- origin: "third-party",
418
- capabilities: REMOTE_EXACT_CAPABILITIES,
419
- fields: [
420
- field({
421
- key: "endpoint",
422
- label: "Endpoint",
423
- scope: "service",
424
- input: "url",
425
- required: true,
426
- defaultValue: "https://api.retaindb.com"
427
- }),
428
- field({
429
- key: "apiKey",
430
- label: "API key",
431
- scope: "service",
432
- input: "secret",
433
- required: true
434
- }),
435
- field({
436
- key: "project",
437
- label: "Project",
438
- scope: "memory",
439
- input: "text",
440
- required: true,
441
- defaultValue: "dsh"
442
- }),
443
- field({
444
- key: "userId",
445
- label: "User ID",
446
- scope: "memory",
447
- input: "text",
448
- required: true,
449
- defaultValue: "dsh-user"
450
- })
451
- ]
452
- },
453
- {
454
- id: "byterover",
455
- label: "ByteRover",
456
- kind: "local",
457
- workspaceBinding: "optional-override",
458
- summary: "Local-first hierarchical knowledge tree accessed through the brv CLI.",
459
- origin: "third-party",
460
- capabilities: {
461
- ...REMOTE_EXACT_CAPABILITIES,
462
- browse: false,
463
- forget: false,
464
- writeMode: "async-extracting",
465
- deletionMode: "unsupported"
466
- },
467
- fields: [
468
- field({
469
- key: "cliPath",
470
- label: "brv executable",
471
- scope: "service",
472
- input: "path",
473
- required: false,
474
- defaultValue: "brv"
475
- }),
476
- field({
477
- key: "defaultDirectory",
478
- label: "Default knowledge directory",
479
- scope: "service",
480
- role: "global-location",
481
- input: "path",
482
- required: false
483
- }),
484
- field({
485
- key: "workingDirectory",
486
- label: "Knowledge directory",
487
- scope: "memory",
488
- input: "path",
489
- required: false
490
- }),
491
- field({
492
- key: "apiKey",
493
- label: "Cloud API key",
494
- scope: "service",
495
- input: "secret",
496
- required: false
497
- })
498
- ]
499
- },
500
- {
501
- id: "supermemory",
502
- label: "Supermemory",
503
- kind: "remote",
504
- workspaceBinding: "provider-global",
505
- summary: "Semantic memory, persistent profiles, conversation ingest, and multi-container recall.",
506
- origin: "third-party",
507
- capabilities: {
508
- ...REMOTE_EXACT_CAPABILITIES,
509
- writeMode: "async-extracting",
510
- deletionMode: "soft"
511
- },
512
- fields: [
513
- field({
514
- key: "endpoint",
515
- label: "Endpoint",
516
- scope: "service",
517
- input: "url",
518
- required: true,
519
- defaultValue: "https://api.supermemory.ai"
520
- }),
521
- field({
522
- key: "apiKey",
523
- label: "API key",
524
- scope: "service",
525
- input: "secret",
526
- required: true
527
- }),
528
- field({
529
- key: "containerTag",
530
- label: "Container tag",
531
- scope: "memory",
532
- input: "text",
533
- required: true,
534
- defaultValue: "dsh"
535
- }),
536
- field({
537
- key: "searchMode",
538
- label: "Search mode",
539
- scope: "memory",
540
- input: "select",
541
- required: true,
542
- defaultValue: "hybrid",
543
- options: [
544
- {
545
- value: "hybrid",
546
- label: "Hybrid"
547
- },
548
- {
549
- value: "memories",
550
- label: "Memories"
551
- },
552
- {
553
- value: "documents",
554
- label: "Documents"
555
- }
556
- ]
557
- })
558
- ]
559
- }
560
- ];
561
- function memoryProviderDescriptor(id) {
562
- const descriptor = MEMORY_PROVIDER_CATALOG.find((candidate) => candidate.id === id);
563
- if (descriptor === void 0) throw new Error(`unsupported memory provider: ${String(id)}`);
564
- return descriptor;
565
- }
566
- function isMemoryProviderId(value) {
567
- return typeof value === "string" && MEMORY_PROVIDER_ID_SET.has(value);
568
- }
569
- function normalizeUrl(value, label) {
570
- const normalized = value.trim().replace(/\/+$/u, "");
571
- let url;
572
- try {
573
- url = new URL(normalized);
574
- } catch {
575
- throw new Error(`${label} must be a valid http(s) URL`);
576
- }
577
- if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error(`${label} must use http or https`);
578
- if (url.username !== "" || url.password !== "") throw new Error(`${label} must not contain credentials`);
579
- return normalized;
580
- }
581
- function normalizeString(value, field) {
582
- const normalized = typeof value === "string" ? value.trim() : value === void 0 || value === null ? "" : String(value).trim();
583
- if (normalized.length > (field.input === "secret" ? 8e3 : 2e3)) throw new Error(`${field.label} is too long`);
584
- if (field.required && normalized === "") throw new Error(`${field.label} is required`);
585
- if (field.input === "url" && normalized !== "") return normalizeUrl(normalized, field.label);
586
- if (field.options !== void 0 && normalized !== "" && !field.options.some((option) => option.value === normalized)) throw new Error(`${field.label} has an unsupported value`);
587
- return normalized;
588
- }
589
- function validateProviderSpecific(providerId, output) {
590
- if (providerId === "openviking" && output.targetUri !== void 0) {
591
- const targetUri = String(output.targetUri).replace(/\/+$/u, "");
592
- if (!/^viking:\/\/user(?:\/[^/]+)?\/memories$/u.test(targetUri)) throw new Error("OpenViking memory URI must be a viking://user/.../memories root");
593
- output.targetUri = targetUri;
594
- }
595
- if (providerId === "holographic") for (const key of ["defaultTrust", "minTrust"]) {
596
- if (output[key] === void 0) continue;
597
- const value = Number(output[key]);
598
- if (value < 0 || value > 1) throw new Error(`${key} must be within 0..1`);
599
- }
600
- if (providerId === "supermemory" && output.containerTag !== void 0) {
601
- const containerTag = String(output.containerTag);
602
- if (!/^[a-zA-Z0-9_:-]+$/u.test(containerTag) || containerTag.length > 100) throw new Error("Supermemory container tag may contain only letters, numbers, _, :, and - (max 100 characters)");
603
- }
604
- }
605
- function normalizeScopedProviderConnection(providerId, scope, input, previous = {}, clearSecrets = []) {
606
- const descriptor = memoryProviderDescriptor(providerId);
607
- if (providerId === "mnemon-native") return {};
608
- const fields = descriptor.fields.filter((item) => item.scope === scope);
609
- const allowed = new Set(fields.map((item) => item.key));
610
- for (const key of Object.keys(input ?? {})) if (!allowed.has(key)) throw new Error(`unsupported ${descriptor.label} ${scope} setting: ${key}`);
611
- for (const key of clearSecrets) if (fields.find((item) => item.key === key)?.input !== "secret") throw new Error(`cannot clear non-secret ${descriptor.label} ${scope} setting: ${key}`);
612
- const output = {};
613
- for (const configField of fields) {
614
- if (clearSecrets.includes(configField.key)) {
615
- output[configField.key] = "";
616
- continue;
617
- }
618
- const value = input?.[configField.key] ?? previous[configField.key] ?? configField.defaultValue;
619
- if (configField.input === "boolean") {
620
- if (value === void 0) continue;
621
- if (typeof value === "boolean") output[configField.key] = value;
622
- else if (value === "true" || value === "false") output[configField.key] = value === "true";
623
- else throw new Error(`${configField.label} must be true or false`);
624
- continue;
625
- }
626
- if (configField.input === "number") {
627
- if (value === void 0 || value === "") continue;
628
- const parsed = typeof value === "number" ? value : Number(value);
629
- if (!Number.isFinite(parsed)) throw new Error(`${configField.label} must be a finite number`);
630
- output[configField.key] = parsed;
631
- continue;
632
- }
633
- const normalized = normalizeString(value, configField);
634
- if (normalized !== "" || configField.required || configField.input === "secret") output[configField.key] = normalized;
635
- }
636
- validateProviderSpecific(providerId, output);
637
- return output;
638
- }
639
- function providerServiceFields(providerId) {
640
- return memoryProviderDescriptor(providerId).fields.filter((field) => field.scope === "service");
641
- }
642
- function splitProviderConnection(providerId, connection) {
643
- const serviceKeys = new Set(providerServiceFields(providerId).map((field) => field.key));
644
- return {
645
- service: Object.fromEntries(Object.entries(connection ?? {}).filter(([key]) => serviceKeys.has(key))),
646
- memory: Object.fromEntries(Object.entries(connection ?? {}).filter(([key]) => !serviceKeys.has(key)))
647
- };
648
- }
649
- function normalizeProviderServiceConnection(providerId, input, previous = {}, clearSecrets = []) {
650
- return normalizeScopedProviderConnection(providerId, "service", input, previous, clearSecrets);
651
- }
652
- function normalizeProviderMemoryConnection(providerId, input, previous = {}) {
653
- return normalizeScopedProviderConnection(providerId, "memory", input, previous);
654
- }
655
- function normalizeProviderConnection(providerId, input, previous = {}, clearSecrets = []) {
656
- const descriptor = memoryProviderDescriptor(providerId);
657
- if (providerId === "mnemon-native") return {};
658
- const allowed = new Set(descriptor.fields.map((item) => item.key));
659
- for (const key of Object.keys(input ?? {})) if (!allowed.has(key)) throw new Error(`unsupported ${descriptor.label} setting: ${key}`);
660
- for (const key of clearSecrets) if (descriptor.fields.find((item) => item.key === key)?.input !== "secret") throw new Error(`cannot clear non-secret ${descriptor.label} setting: ${key}`);
661
- const output = {};
662
- for (const configField of descriptor.fields) {
663
- if (clearSecrets.includes(configField.key)) {
664
- output[configField.key] = "";
665
- continue;
666
- }
667
- const supplied = input?.[configField.key];
668
- const fallback = previous[configField.key] ?? configField.defaultValue;
669
- const value = supplied ?? fallback;
670
- if (configField.input === "boolean") {
671
- if (value === void 0) continue;
672
- if (typeof value === "boolean") output[configField.key] = value;
673
- else if (value === "true" || value === "false") output[configField.key] = value === "true";
674
- else throw new Error(`${configField.label} must be true or false`);
675
- continue;
676
- }
677
- if (configField.input === "number") {
678
- if (value === void 0 || value === "") continue;
679
- const parsed = typeof value === "number" ? value : Number(value);
680
- if (!Number.isFinite(parsed)) throw new Error(`${configField.label} must be a finite number`);
681
- output[configField.key] = parsed;
682
- continue;
683
- }
684
- const normalized = normalizeString(value, configField);
685
- if (normalized !== "" || configField.required || configField.input === "secret") output[configField.key] = normalized;
686
- }
687
- validateProviderSpecific(providerId, output);
688
- return output;
689
- }
690
- function publicScopedProviderConnection(providerId, scope, connection) {
691
- const fields = memoryProviderDescriptor(providerId).fields.filter((item) => item.scope === scope);
692
- const keys = new Set(fields.map((item) => item.key));
693
- const secrets = new Set(fields.filter((item) => item.input === "secret").map((item) => item.key));
694
- return {
695
- settings: Object.fromEntries(Object.entries(connection).filter(([key]) => keys.has(key) && !secrets.has(key))),
696
- configuredSecrets: [...secrets].filter((key) => String(connection[key] ?? "") !== "")
697
- };
698
- }
699
- function publicProviderConnection(providerId, connection) {
700
- const descriptor = memoryProviderDescriptor(providerId);
701
- const secrets = new Set(descriptor.fields.filter((item) => item.input === "secret").map((item) => item.key));
702
- return {
703
- settings: Object.fromEntries(Object.entries(connection).filter(([key]) => !secrets.has(key))),
704
- configuredSecrets: [...secrets].filter((key) => String(connection[key] ?? "") !== "")
705
- };
706
- }
707
- //#endregion
708
- //#region src/providers/provider.ts
709
- const NORMALIZED_RELEVANCE_SCORE = Object.freeze({ kind: "normalized-relevance" });
710
- //#endregion
711
- //#region src/providers/byterover.ts
712
- var ByteRoverProvider = class {
713
- memoryBodies;
714
- id = "byterover";
715
- scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
716
- process;
717
- queryTimeoutMs;
718
- curateTimeoutMs;
719
- statusCache = /* @__PURE__ */ new Map();
720
- statusInFlight = /* @__PURE__ */ new Map();
721
- constructor(memoryBodies, options = {}) {
722
- this.memoryBodies = memoryBodies;
723
- this.process = options.process ?? runProcess;
724
- this.queryTimeoutMs = options.queryTimeoutMs ?? 1e4;
725
- this.curateTimeoutMs = options.curateTimeoutMs ?? 12e4;
726
- }
727
- async discover(connection) {
728
- const configured = String(connection.defaultDirectory ?? "").trim();
729
- const existingDirectory = this.memoryBodies.list().find((body) => body.provider.id === this.id)?.provider.settings.workingDirectory;
730
- const directory = configured === "" ? String(existingDirectory ?? "").trim() || join(this.memoryBodies.runner.effectiveDataDir(), "state", "byterover", "default") : isAbsolute(configured) ? configured : resolve(this.memoryBodies.runner.effectiveDataDir(), configured);
731
- return [{
732
- externalId: directory,
733
- name: basename(directory) || "ByteRover",
734
- description: `ByteRover knowledge directory at ${directory}`,
735
- connection: { workingDirectory: directory }
736
- }];
737
- }
738
- async status(body, signal) {
739
- if (signal !== void 0) return this.checkStatus(body, signal);
740
- const cached = this.statusCache.get(body.id);
741
- if (cached !== void 0 && Date.now() - cached.checkedAt < 6e4) return cached.value;
742
- const running = this.statusInFlight.get(body.id);
743
- if (running !== void 0) return running;
744
- const pending = this.checkStatus(body);
745
- this.statusInFlight.set(body.id, pending);
746
- try {
747
- const value = await pending;
748
- this.statusCache.set(body.id, {
749
- checkedAt: Date.now(),
750
- value
751
- });
752
- return value;
753
- } finally {
754
- if (this.statusInFlight.get(body.id) === pending) this.statusInFlight.delete(body.id);
755
- }
756
- }
757
- invalidateStatus(memoryBodyId) {
758
- if (memoryBodyId === void 0) this.statusCache.clear();
759
- else this.statusCache.delete(memoryBodyId);
760
- }
761
- async checkStatus(body, signal) {
762
- try {
763
- await this.run(body, ["status"], 15e3, signal);
764
- return { healthy: true };
765
- } catch (error) {
766
- return {
767
- healthy: false,
768
- error: error instanceof Error ? error.message : String(error)
769
- };
770
- }
771
- }
772
- async search(body, request, signal) {
773
- const output = await this.run(body, [
774
- "query",
775
- "--",
776
- request.query.slice(0, 5e3)
777
- ], this.queryTimeoutMs, signal);
778
- if (output.length < 20) return {
779
- results: [],
780
- hint: "ByteRover found no relevant memories."
781
- };
782
- const content = output.length > 8e3 ? `${output.slice(0, 8e3)}\n\n[... truncated]` : output;
783
- return { results: [{
784
- id: `byterover:${createHash("sha256").update(content).digest("hex").slice(0, 24)}`,
785
- content,
786
- category: "context",
787
- source: "external",
788
- score: 1
789
- }] };
790
- }
791
- async graph(body) {
792
- this.connection(body);
793
- return {
794
- nodes: [],
795
- edges: [],
796
- generatedAt: (/* @__PURE__ */ new Date()).toISOString()
797
- };
798
- }
799
- async list(body, request, signal) {
800
- if (request.query === void 0 || request.query.trim() === "") {
801
- this.connection(body);
802
- return [];
803
- }
804
- return (await this.search(body, {
805
- query: request.query,
806
- ...request.limit === void 0 ? {} : { limit: request.limit }
807
- }, signal)).results;
808
- }
809
- async remember(body, request, signal) {
810
- await this.run(body, [
811
- "curate",
812
- "--",
813
- request.content
814
- ], this.curateTimeoutMs, signal);
815
- return {
816
- action: "stored",
817
- provider: this.id,
818
- summary: "ByteRover curated the memory into its knowledge tree."
819
- };
820
- }
821
- connection(body) {
822
- if (body.provider.id !== this.id) throw new Error(`ByteRover cannot serve provider ${body.provider.id}`);
823
- return this.memoryBodies.providerConnection(body.id, this.id);
824
- }
825
- async run(body, args, timeoutMs, signal) {
826
- const connection = this.connection(body);
827
- const command = String(connection.cliPath ?? "brv");
828
- const configuredDirectory = String(connection.workingDirectory ?? connection.defaultDirectory ?? "").trim();
829
- const defaultDirectory = join(this.memoryBodies.runner.effectiveDataDir(), "state", "byterover", "default");
830
- const cwd = configuredDirectory === "" ? defaultDirectory : isAbsolute(configuredDirectory) ? configuredDirectory : resolve(this.memoryBodies.runner.effectiveDataDir(), configuredDirectory);
831
- mkdirSync(cwd, {
832
- recursive: true,
833
- mode: 448
834
- });
835
- const apiKey = String(connection.apiKey ?? "").trim();
836
- const result = await this.process(command, args, {
837
- timeoutMs,
838
- maxOutputBytes: 262144,
839
- ...signal === void 0 ? {} : { signal },
840
- cwd,
841
- label: "ByteRover",
842
- env: {
843
- ...process.env,
844
- ...apiKey === "" ? {} : { BRV_API_KEY: apiKey }
845
- }
846
- });
847
- const stdout = result.stdout.trim();
848
- const stderr = result.stderr.trim();
849
- if (result.exitCode !== 0) throw new Error(stderr || stdout || `ByteRover exited with code ${String(result.exitCode)}`);
850
- return stdout;
851
- }
852
- };
853
- //#endregion
854
- //#region src/providers/http.ts
855
- function jsonObject(value) {
856
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
857
- }
858
- function jsonString(value) {
859
- return typeof value === "string" ? value : void 0;
860
- }
861
- function jsonNumber(value) {
862
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
863
- }
864
- function jsonArray(value) {
865
- return Array.isArray(value) ? value : [];
866
- }
867
- function firstArray(value, ...keys) {
868
- if (Array.isArray(value)) return value;
869
- const root = jsonObject(value);
870
- for (const key of keys) if (Array.isArray(root?.[key])) return root[key];
871
- const nested = jsonObject(root?.data);
872
- for (const key of keys) if (Array.isArray(nested?.[key])) return nested[key];
873
- return [];
874
- }
875
- function errorDetail(payload) {
876
- if (typeof payload === "string") return payload.trim() || void 0;
877
- const root = jsonObject(payload);
878
- const direct = jsonString(root?.message) ?? jsonString(root?.error) ?? jsonString(root?.detail);
879
- if (direct !== void 0) return direct;
880
- const error = jsonObject(root?.error);
881
- return jsonString(error?.message) ?? jsonString(error?.detail);
882
- }
883
- /** Shared timeout, cancellation, error, and projection behavior for HTTP providers. */
884
- var HttpMemoryProvider = class {
885
- memoryBodies;
886
- requestFetch;
887
- requestTimeoutMs;
888
- constructor(memoryBodies, options = {}) {
889
- this.memoryBodies = memoryBodies;
890
- this.requestFetch = options.fetch ?? globalThis.fetch;
891
- this.requestTimeoutMs = options.requestTimeoutMs ?? 15e3;
892
- }
893
- async graph(body, signal) {
894
- return {
895
- nodes: (await this.list(body, { limit: 200 }, signal)).map((item) => ({
896
- ...item,
897
- color: "#6574d9"
898
- })),
899
- edges: [],
900
- generatedAt: (/* @__PURE__ */ new Date()).toISOString()
901
- };
902
- }
903
- connection(body) {
904
- if (body.provider.id !== this.id) throw new Error(`${this.id} cannot serve provider ${body.provider.id}`);
905
- return this.memoryBodies.providerConnection(body.id, this.id);
906
- }
907
- async request(body, path, options = {}) {
908
- const connection = this.connection(body);
909
- return this.requestConnection(connection, path, options);
910
- }
911
- async requestConnection(connection, path, options = {}) {
912
- const endpoint = String(connection.endpoint ?? "").replace(/\/+$/u, "");
913
- const label = memoryProviderDescriptor(this.id).label;
914
- if (endpoint === "") throw new Error(`${label} endpoint is not configured`);
915
- if (!path.startsWith("/")) throw new Error(`${label} request path must be absolute`);
916
- options.signal?.throwIfAborted();
917
- const controller = new AbortController();
918
- const relay = () => controller.abort(options.signal?.reason);
919
- options.signal?.addEventListener("abort", relay, { once: true });
920
- const timeoutMs = options.timeoutMs ?? this.requestTimeoutMs;
921
- const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error(`${label} request timed out`)), timeoutMs);
922
- const headers = new Headers(options.headers);
923
- if (options.json !== void 0 && !headers.has("Content-Type")) headers.set("Content-Type", "application/json");
924
- try {
925
- const response = await this.requestFetch(`${endpoint}${path}`, {
926
- method: options.method ?? (options.json === void 0 ? "GET" : "POST"),
927
- headers,
928
- ...options.json === void 0 ? {} : { body: JSON.stringify(options.json) },
929
- signal: controller.signal
930
- });
931
- const raw = await response.text();
932
- let payload = {};
933
- if (raw !== "") try {
934
- payload = JSON.parse(raw);
935
- } catch {
936
- payload = raw;
937
- }
938
- if (!response.ok) {
939
- const detail = errorDetail(payload);
940
- throw new Error(`${label} HTTP ${response.status}${detail === void 0 ? "" : `: ${detail}`}`);
941
- }
942
- return payload;
943
- } catch (error) {
944
- if (controller.signal.aborted && options.signal?.aborted !== true) throw new Error(`${label} request timed out after ${timeoutMs}ms`);
945
- throw error;
946
- } finally {
947
- clearTimeout(timer);
948
- options.signal?.removeEventListener("abort", relay);
949
- }
950
- }
951
- };
952
- //#endregion
953
- //#region src/providers/hindsight.ts
954
- function insight$5(value) {
955
- const item = jsonObject(value);
956
- const id = jsonString(item?.id);
957
- const content = jsonString(item?.text) ?? jsonString(item?.content) ?? jsonString(item?.label);
958
- if (id === void 0 || content === void 0) return void 0;
959
- const score = jsonNumber(jsonObject(item?.scores)?.final) ?? jsonNumber(item?.score);
960
- const createdAt = jsonString(item?.mentioned_at) ?? jsonString(item?.date) ?? jsonString(item?.occurred_start);
961
- const rawEntities = item?.entities;
962
- const entities = Array.isArray(rawEntities) ? rawEntities.filter((entry) => typeof entry === "string") : typeof rawEntities === "string" ? rawEntities.split(",").map((entry) => entry.replace(/\s*\([^)]*\)\s*$/u, "").trim()).filter(Boolean) : [];
963
- const tags = jsonArray(item?.tags).filter((entry) => typeof entry === "string");
964
- return {
965
- id,
966
- content,
967
- category: jsonString(item?.type) ?? jsonString(item?.fact_type) ?? "general",
968
- source: "external",
969
- ...score === void 0 ? {} : { score },
970
- ...createdAt === void 0 ? {} : { createdAt },
971
- ...entities.length === 0 ? {} : { entities },
972
- ...tags.length === 0 ? {} : { tags }
973
- };
974
- }
975
- function edgeType(value) {
976
- return value === "temporal" || value === "semantic" || value === "causal" || value === "entity" ? value : void 0;
977
- }
978
- var HindsightProvider = class extends HttpMemoryProvider {
979
- id = "hindsight";
980
- scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
981
- constructor(memoryBodies, options = {}) {
982
- super(memoryBodies, options);
983
- }
984
- async discover(connection, signal) {
985
- return firstArray(await this.requestConnection(connection, "/v1/default/banks", {
986
- headers: this.headers(connection),
987
- signal
988
- }), "banks", "items").flatMap((value) => {
989
- const item = jsonObject(value);
990
- const id = jsonString(item?.bank_id) ?? jsonString(item?.id);
991
- if (id === void 0) return [];
992
- const description = jsonString(item?.mission)?.trim() || jsonString(item?.description)?.trim() || `Hindsight memory bank ${id}`;
993
- return [{
994
- externalId: id,
995
- name: jsonString(item?.name) ?? id,
996
- description,
997
- connection: {
998
- bankId: id,
999
- budget: "mid"
1000
- }
1001
- }];
1002
- });
1003
- }
1004
- async status(body, signal) {
1005
- try {
1006
- const connection = this.connection(body);
1007
- await this.request(body, "/health/live", {
1008
- headers: this.headers(connection),
1009
- signal
1010
- });
1011
- try {
1012
- const [statsPayload, entitiesPayload] = await Promise.all([this.request(body, `${this.bankPath(connection)}/stats`, {
1013
- headers: this.headers(connection),
1014
- signal
1015
- }), this.request(body, `${this.bankPath(connection)}/entities?limit=100&offset=0`, {
1016
- headers: this.headers(connection),
1017
- signal
1018
- })]);
1019
- const stats = jsonObject(statsPayload) ?? {};
1020
- const byFactType = jsonObject(stats.nodes_by_fact_type) ?? {};
1021
- const byCategory = Object.fromEntries(Object.entries(byFactType).flatMap(([category, count]) => {
1022
- const value = jsonNumber(count);
1023
- return value === void 0 ? [] : [[category, value]];
1024
- }));
1025
- const operations = jsonObject(stats.operations_by_status) ?? {};
1026
- const topEntities = firstArray(entitiesPayload, "items").flatMap((value) => {
1027
- const item = jsonObject(value);
1028
- const entity = jsonString(item?.canonical_name);
1029
- const count = jsonNumber(item?.mention_count);
1030
- return entity === void 0 || count === void 0 ? [] : [{
1031
- entity,
1032
- count
1033
- }];
1034
- });
1035
- return {
1036
- healthy: true,
1037
- stats: {
1038
- totalInsights: jsonNumber(stats.total_nodes) ?? 0,
1039
- deletedInsights: 0,
1040
- edgeCount: jsonNumber(stats.total_links) ?? 0,
1041
- oplogCount: Object.values(operations).reduce((total, value) => total + (jsonNumber(value) ?? 0), 0),
1042
- dbSizeBytes: 0,
1043
- byCategory,
1044
- topEntities
1045
- }
1046
- };
1047
- } catch {
1048
- return { healthy: true };
1049
- }
1050
- } catch (error) {
1051
- return {
1052
- healthy: false,
1053
- error: error instanceof Error ? error.message : String(error)
1054
- };
1055
- }
1056
- }
1057
- async search(body, request, signal) {
1058
- const connection = this.connection(body);
1059
- return { results: firstArray(await this.request(body, `${this.bankPath(connection)}/memories/recall`, {
1060
- headers: this.headers(connection),
1061
- json: {
1062
- query: request.query,
1063
- budget: String(connection.budget ?? "mid"),
1064
- max_tokens: Math.min(Math.max((request.limit ?? 10) * 400, 400), 8e3),
1065
- types: [
1066
- "world",
1067
- "experience",
1068
- "observation"
1069
- ],
1070
- prefer_observations: true
1071
- },
1072
- signal
1073
- }), "results", "items").map(insight$5).filter((item) => item !== void 0).slice(0, request.limit ?? 10) };
1074
- }
1075
- async list(body, request, signal) {
1076
- const connection = this.connection(body);
1077
- const params = new URLSearchParams({
1078
- limit: String(Math.min(Math.max(request.limit ?? 200, 1), 1e3)),
1079
- offset: "0",
1080
- state: "valid"
1081
- });
1082
- if (request.query !== void 0 && request.query.trim() !== "") params.set("q", request.query.trim());
1083
- return firstArray(await this.request(body, `${this.bankPath(connection)}/memories/list?${params}`, {
1084
- headers: this.headers(connection),
1085
- signal
1086
- }), "items", "results").map(insight$5).filter((item) => item !== void 0).filter((item) => request.category === void 0 || item.category === request.category);
1087
- }
1088
- async graph(body, signal) {
1089
- const connection = this.connection(body);
1090
- const payload = jsonObject(await this.request(body, `${this.bankPath(connection)}/graph?limit=1000`, {
1091
- headers: this.headers(connection),
1092
- signal
1093
- })) ?? {};
1094
- return {
1095
- nodes: jsonArray(payload.nodes).flatMap((value) => {
1096
- const item = jsonObject(value);
1097
- const data = jsonObject(item?.data) ?? item;
1098
- const projected = insight$5(data);
1099
- return projected === void 0 ? [] : [{
1100
- ...projected,
1101
- color: jsonString(data?.color) ?? "#6574d9"
1102
- }];
1103
- }),
1104
- edges: jsonArray(payload.edges).flatMap((value) => {
1105
- const item = jsonObject(value);
1106
- const data = jsonObject(item?.data) ?? item;
1107
- const sourceId = jsonString(data?.from) ?? jsonString(data?.source);
1108
- const targetId = jsonString(data?.to) ?? jsonString(data?.target);
1109
- if (sourceId === void 0 || targetId === void 0) return [];
1110
- const rawType = jsonString(data?.type) ?? jsonString(data?.linkType);
1111
- const type = edgeType(rawType);
1112
- return [{
1113
- sourceId,
1114
- targetId,
1115
- label: rawType ?? "related",
1116
- color: type === "causal" ? "#e74c3c" : type === "entity" ? "#2ecc71" : type === "temporal" ? "#aaaaaa" : "#3498db",
1117
- ...type === void 0 ? {} : { type }
1118
- }];
1119
- }),
1120
- generatedAt: (/* @__PURE__ */ new Date()).toISOString()
1121
- };
1122
- }
1123
- async related(body, id, depth, _edge, signal) {
1124
- const graph = await this.graph(body, signal);
1125
- let frontier = /* @__PURE__ */ new Set([id]);
1126
- const visited = /* @__PURE__ */ new Set([id]);
1127
- for (let level = 0; level < depth; level += 1) {
1128
- const next = /* @__PURE__ */ new Set();
1129
- for (const edge of graph.edges) {
1130
- if (frontier.has(edge.sourceId) && !visited.has(edge.targetId)) next.add(edge.targetId);
1131
- if (frontier.has(edge.targetId) && !visited.has(edge.sourceId)) next.add(edge.sourceId);
1132
- }
1133
- for (const value of next) visited.add(value);
1134
- frontier = next;
1135
- }
1136
- return graph.nodes.filter((node) => node.id !== id && visited.has(node.id)).map(({ color: _color, ...node }) => node);
1137
- }
1138
- async remember(body, request, signal) {
1139
- const connection = this.connection(body);
1140
- const operationId = randomUUID();
1141
- const payload = jsonObject(await this.request(body, `${this.bankPath(connection)}/memories`, {
1142
- headers: this.headers(connection),
1143
- json: {
1144
- items: [{
1145
- content: request.content,
1146
- context: request.category ?? "dsh-mnemon",
1147
- metadata: { source: "dsh-mnemon" },
1148
- ...request.tags === void 0 ? {} : { tags: request.tags },
1149
- ...request.entities === void 0 ? {} : { entities: request.entities.map((text) => ({ text })) }
1150
- }],
1151
- async: true,
1152
- operation_id: operationId
1153
- },
1154
- signal
1155
- })) ?? {};
1156
- return {
1157
- action: "stored",
1158
- provider: this.id,
1159
- summary: "Hindsight queued the content for structured memory extraction.",
1160
- operationId: jsonString(payload.operation_id) ?? operationId,
1161
- ...jsonNumber(payload.items_count) === void 0 ? {} : { itemsCount: jsonNumber(payload.items_count) }
1162
- };
1163
- }
1164
- async forget(body, id, signal) {
1165
- const connection = this.connection(body);
1166
- await this.request(body, `${this.bankPath(connection)}/memories/${encodeURIComponent(id)}`, {
1167
- method: "PATCH",
1168
- headers: this.headers(connection),
1169
- json: {
1170
- state: "invalidated",
1171
- reason: "Forgotten from dsh-mnemon"
1172
- },
1173
- signal
1174
- });
1175
- return {
1176
- action: "invalidated",
1177
- provider: this.id,
1178
- id
1179
- };
1180
- }
1181
- bankPath(connection) {
1182
- return `/v1/default/banks/${encodeURIComponent(String(connection.bankId))}`;
1183
- }
1184
- headers(connection) {
1185
- const token = String(connection.apiKey ?? "").replace(/^Bearer\s+/iu, "");
1186
- return token === "" ? {} : { Authorization: `Bearer ${token}` };
1187
- }
1188
- };
1189
- //#endregion
1190
- //#region src/providers/holographic.ts
1191
- const WORD = /[\p{L}\p{N}_-]+/gu;
1192
- const CJK = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+/gu;
1193
- const QUOTED = /["“”'‘’]([^"“”'‘’]{2,100})["“”'‘’]/gu;
1194
- const CAPITALIZED = /\b([A-Z][\p{L}\p{N}_-]+(?:\s+[A-Z][\p{L}\p{N}_-]+)*)\b/gu;
1195
- function clampTrust(value) {
1196
- return Math.min(1, Math.max(0, value));
1197
- }
1198
- function terms(value) {
1199
- const normalized = value.toLocaleLowerCase();
1200
- const output = new Set((normalized.match(WORD) ?? []).filter((token) => token.length > 1));
1201
- for (const run of normalized.match(CJK) ?? []) {
1202
- for (const character of run) output.add(character);
1203
- for (let index = 0; index < run.length - 1; index += 1) output.add(run.slice(index, index + 2));
1204
- }
1205
- return output;
1206
- }
1207
- function overlap(left, right) {
1208
- if (left.size === 0 || right.size === 0) return 0;
1209
- let shared = 0;
1210
- for (const value of left) if (right.has(value)) shared += 1;
1211
- return shared / (/* @__PURE__ */ new Set([...left, ...right])).size;
1212
- }
1213
- function extractEntities(content, supplied = []) {
1214
- const values = [...supplied];
1215
- for (const match of content.matchAll(QUOTED)) values.push(match[1]);
1216
- for (const match of content.matchAll(CAPITALIZED)) values.push(match[1]);
1217
- return [...new Set(values.map((value) => value.trim()).filter((value) => value.length >= 2 && value.length <= 100))].slice(0, 50);
1218
- }
1219
- function insight$4(fact, score) {
1220
- return {
1221
- id: fact.id,
1222
- content: fact.content,
1223
- category: fact.category,
1224
- importance: fact.trustScore,
1225
- tags: fact.tags,
1226
- entities: fact.entities,
1227
- source: "external",
1228
- createdAt: fact.createdAt,
1229
- ...score === void 0 ? {} : { score }
1230
- };
1231
- }
1232
- var HolographicProvider = class {
1233
- memoryBodies;
1234
- id = "holographic";
1235
- scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
1236
- constructor(memoryBodies) {
1237
- this.memoryBodies = memoryBodies;
1238
- }
1239
- async discover(connection) {
1240
- const configured = String(connection.dataPath ?? "").trim();
1241
- const path = configured === "" ? join(this.memoryBodies.runner.effectiveDataDir(), "state", "holographic", "store.json") : isAbsolute(configured) ? configured : resolve(this.memoryBodies.runner.effectiveDataDir(), configured);
1242
- const label = basename(path).replace(/\.json$/iu, "") || "Holographic";
1243
- return [{
1244
- externalId: path,
1245
- name: label === "store" ? "Holographic" : label,
1246
- description: `Holographic fact store at ${path}`,
1247
- connection: {
1248
- defaultTrust: .5,
1249
- minTrust: .3
1250
- }
1251
- }];
1252
- }
1253
- async status(body) {
1254
- try {
1255
- const store = this.load(body);
1256
- return {
1257
- healthy: true,
1258
- stats: this.stats(store)
1259
- };
1260
- } catch (error) {
1261
- return {
1262
- healthy: false,
1263
- error: error instanceof Error ? error.message : String(error)
1264
- };
1265
- }
1266
- }
1267
- async search(body, request) {
1268
- const store = this.load(body);
1269
- const connection = this.connection(body);
1270
- const minTrust = clampTrust(Number(connection.minTrust ?? .3));
1271
- const queryTerms = terms(request.query);
1272
- const query = request.query.toLocaleLowerCase();
1273
- const limit = Math.min(Math.max(request.limit ?? 10, 1), 50);
1274
- return { results: store.facts.flatMap((fact) => {
1275
- if (fact.trustScore < minTrust || request.category !== void 0 && fact.category !== request.category) return [];
1276
- const lexical = overlap(queryTerms, terms(`${fact.content} ${fact.tags.join(" ")} ${fact.entities.join(" ")}`));
1277
- const phrase = fact.content.toLocaleLowerCase().includes(query) ? 1 : 0;
1278
- const entity = fact.entities.some((value) => query.includes(value.toLocaleLowerCase())) ? 1 : 0;
1279
- const relevance = Math.max(lexical, phrase * .9, entity * .8);
1280
- return relevance <= 0 ? [] : [{
1281
- fact,
1282
- score: relevance * fact.trustScore
1283
- }];
1284
- }).sort((left, right) => right.score - left.score).slice(0, limit).map((result) => insight$4(result.fact, result.score)) };
1285
- }
1286
- async list(body, request) {
1287
- if (request.query !== void 0 && request.query.trim() !== "") return (await this.search(body, {
1288
- query: request.query,
1289
- ...request.category === void 0 ? {} : { category: request.category },
1290
- ...request.limit === void 0 ? {} : { limit: request.limit }
1291
- })).results;
1292
- const store = this.load(body);
1293
- const minTrust = clampTrust(Number(this.connection(body).minTrust ?? .3));
1294
- return store.facts.filter((fact) => fact.trustScore >= minTrust && (request.category === void 0 || fact.category === request.category)).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt)).slice(0, Math.min(Math.max(request.limit ?? 200, 1), 1e3)).map((fact) => insight$4(fact));
1295
- }
1296
- async graph(body) {
1297
- const facts = await this.list(body, { limit: 500 });
1298
- const entities = [...new Set(facts.flatMap((fact) => fact.entities ?? []))];
1299
- return {
1300
- nodes: [...facts.map((fact) => ({
1301
- ...fact,
1302
- color: "#6574d9",
1303
- kind: "memory"
1304
- })), ...entities.map((entity) => ({
1305
- id: `entity:${encodeURIComponent(entity)}`,
1306
- content: entity,
1307
- color: "#2ecc71",
1308
- kind: "entity"
1309
- }))],
1310
- edges: facts.flatMap((fact) => (fact.entities ?? []).map((entity) => ({
1311
- sourceId: fact.id,
1312
- targetId: `entity:${encodeURIComponent(entity)}`,
1313
- label: "entity",
1314
- color: "#2ecc71",
1315
- type: "entity"
1316
- }))),
1317
- generatedAt: (/* @__PURE__ */ new Date()).toISOString()
1318
- };
1319
- }
1320
- async related(body, id, _depth) {
1321
- const store = this.load(body);
1322
- const source = store.facts.find((fact) => fact.id === id);
1323
- if (source === void 0) return [];
1324
- const sourceEntities = new Set(source.entities.map((value) => value.toLocaleLowerCase()));
1325
- const sourceTerms = terms(source.content);
1326
- return store.facts.flatMap((fact) => {
1327
- if (fact.id === id) return [];
1328
- const sharedEntities = fact.entities.filter((value) => sourceEntities.has(value.toLocaleLowerCase())).length;
1329
- const score = Math.max(sharedEntities === 0 ? 0 : Math.min(1, .5 + sharedEntities * .2), overlap(sourceTerms, terms(fact.content))) * fact.trustScore;
1330
- return score <= 0 ? [] : [{
1331
- fact,
1332
- score
1333
- }];
1334
- }).sort((left, right) => right.score - left.score).slice(0, 20).map((result) => insight$4(result.fact, result.score));
1335
- }
1336
- async remember(body, request) {
1337
- const store = this.load(body);
1338
- const existing = store.facts.find((fact) => fact.content === request.content.trim());
1339
- if (existing !== void 0) return {
1340
- action: "skipped",
1341
- provider: this.id,
1342
- id: existing.id,
1343
- summary: "Holographic already contains this fact."
1344
- };
1345
- const now = (/* @__PURE__ */ new Date()).toISOString();
1346
- const connection = this.connection(body);
1347
- const fact = {
1348
- id: `holo-${randomUUID()}`,
1349
- content: request.content.trim(),
1350
- category: request.category ?? "general",
1351
- tags: [...new Set(request.tags ?? [])],
1352
- entities: extractEntities(request.content, request.entities),
1353
- trustScore: clampTrust(Number(request.importance ?? connection.defaultTrust ?? .5)),
1354
- createdAt: now,
1355
- updatedAt: now
1356
- };
1357
- store.facts.push(fact);
1358
- this.save(body, store);
1359
- return {
1360
- action: "stored",
1361
- provider: this.id,
1362
- id: fact.id,
1363
- summary: "Holographic stored the structured fact."
1364
- };
1365
- }
1366
- async forget(body, id) {
1367
- const store = this.load(body);
1368
- const before = store.facts.length;
1369
- store.facts = store.facts.filter((fact) => fact.id !== id);
1370
- if (store.facts.length === before) throw new Error(`unknown Holographic fact: ${id}`);
1371
- this.save(body, store);
1372
- return {
1373
- action: "deleted",
1374
- provider: this.id,
1375
- id
1376
- };
1377
- }
1378
- connection(body) {
1379
- if (body.provider.id !== this.id) throw new Error(`Holographic cannot serve provider ${body.provider.id}`);
1380
- return this.memoryBodies.providerConnection(body.id, this.id);
1381
- }
1382
- path(body) {
1383
- const configured = String(this.connection(body).dataPath ?? "").trim();
1384
- if (configured === "") return join(this.memoryBodies.runner.effectiveDataDir(), "state", "holographic", "store.json");
1385
- return isAbsolute(configured) ? configured : resolve(this.memoryBodies.runner.effectiveDataDir(), configured);
1386
- }
1387
- load(body) {
1388
- const path = this.path(body);
1389
- if (!existsSync(path)) return {
1390
- version: 1,
1391
- facts: []
1392
- };
1393
- const value = JSON.parse(readFileSync(path, "utf8"));
1394
- if (value.version !== 1 || !Array.isArray(value.facts)) throw new Error(`invalid Holographic fact store: ${path}`);
1395
- return {
1396
- version: 1,
1397
- facts: value.facts
1398
- };
1399
- }
1400
- save(body, store) {
1401
- const path = this.path(body);
1402
- mkdirSync(dirname(path), {
1403
- recursive: true,
1404
- mode: 448
1405
- });
1406
- const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
1407
- writeFileSync(temporary, `${JSON.stringify(store, null, 2)}\n`, {
1408
- encoding: "utf8",
1409
- mode: 384
1410
- });
1411
- renameSync(temporary, path);
1412
- chmodSync(path, 384);
1413
- }
1414
- stats(store) {
1415
- const byCategory = {};
1416
- const entityCounts = /* @__PURE__ */ new Map();
1417
- for (const fact of store.facts) {
1418
- byCategory[fact.category] = (byCategory[fact.category] ?? 0) + 1;
1419
- for (const entity of fact.entities) entityCounts.set(entity, (entityCounts.get(entity) ?? 0) + 1);
1420
- }
1421
- return {
1422
- totalInsights: store.facts.length,
1423
- deletedInsights: 0,
1424
- edgeCount: store.facts.reduce((total, fact) => total + fact.entities.length, 0),
1425
- oplogCount: 0,
1426
- dbSizeBytes: Buffer.byteLength(JSON.stringify(store)),
1427
- byCategory,
1428
- topEntities: [...entityCounts].map(([entity, count]) => ({
1429
- entity,
1430
- count
1431
- })).sort((left, right) => right.count - left.count).slice(0, 20)
1432
- };
1433
- }
1434
- };
1435
- //#endregion
1436
- //#region src/providers/honcho.ts
1437
- function insight$3(value) {
1438
- const item = jsonObject(value);
1439
- const id = jsonString(item?.id);
1440
- const content = jsonString(item?.content);
1441
- if (id === void 0 || content === void 0) return void 0;
1442
- const observer = jsonString(item?.observer_id) ?? jsonString(item?.observer);
1443
- const observed = jsonString(item?.observed_id) ?? jsonString(item?.observed);
1444
- const createdAt = jsonString(item?.created_at) ?? jsonString(item?.createdAt);
1445
- const entities = [observer, observed].filter((entry) => entry !== void 0);
1446
- return {
1447
- id,
1448
- content,
1449
- category: jsonString(item?.level) ?? "insight",
1450
- source: "external",
1451
- ...createdAt === void 0 ? {} : { createdAt },
1452
- ...entities.length === 0 ? {} : { entities }
1453
- };
1454
- }
1455
- var HonchoProvider = class extends HttpMemoryProvider {
1456
- id = "honcho";
1457
- constructor(memoryBodies, options = {}) {
1458
- super(memoryBodies, options);
1459
- }
1460
- async discover(connection, signal) {
1461
- return firstArray(await this.requestConnection(connection, "/v3/workspaces/list?page=1&size=100", {
1462
- headers: this.headers(connection),
1463
- json: {},
1464
- signal
1465
- }), "items", "results").flatMap((value) => {
1466
- const item = jsonObject(value);
1467
- const id = jsonString(item?.id);
1468
- if (id === void 0) return [];
1469
- const metadata = jsonObject(item?.metadata);
1470
- return [{
1471
- externalId: id,
1472
- name: jsonString(metadata?.name) ?? jsonString(metadata?.title) ?? id,
1473
- description: jsonString(metadata?.description) ?? `Honcho workspace ${id}`,
1474
- connection: {
1475
- workspace: id,
1476
- userId: "*",
1477
- agentId: "*"
1478
- }
1479
- }];
1480
- });
1481
- }
1482
- async status(body, signal) {
1483
- try {
1484
- await this.list(body, { limit: 1 }, signal);
1485
- return { healthy: true };
1486
- } catch (error) {
1487
- return {
1488
- healthy: false,
1489
- error: error instanceof Error ? error.message : String(error)
1490
- };
1491
- }
1492
- }
1493
- async search(body, request, signal) {
1494
- const connection = this.connection(body);
1495
- return { results: firstArray(await this.request(body, `${this.basePath(connection)}/conclusions/query`, {
1496
- headers: this.headers(connection),
1497
- json: {
1498
- query: request.query,
1499
- top_k: Math.min(request.limit ?? 10, 100),
1500
- filters: this.scope(connection, true)
1501
- },
1502
- signal
1503
- }), "items", "results").map(insight$3).filter((item) => item !== void 0) };
1504
- }
1505
- async list(body, request, signal) {
1506
- const connection = this.connection(body);
1507
- const limit = Math.min(Math.max(request.limit ?? 200, 1), 100);
1508
- return firstArray(await this.request(body, `${this.basePath(connection)}/conclusions/list?page=1&size=${limit}`, {
1509
- headers: this.headers(connection),
1510
- json: { filters: {
1511
- ...this.scope(connection),
1512
- ...request.category === void 0 ? {} : { level: request.category }
1513
- } },
1514
- signal
1515
- }), "items", "results").map(insight$3).filter((item) => item !== void 0);
1516
- }
1517
- async remember(body, request, signal) {
1518
- const connection = this.connection(body);
1519
- const created = firstArray(await this.request(body, `${this.basePath(connection)}/conclusions`, {
1520
- headers: this.headers(connection),
1521
- json: { conclusions: [{
1522
- content: request.content,
1523
- observer_id: String(connection.agentId) === "*" ? "dsh" : String(connection.agentId),
1524
- observed_id: String(connection.userId) === "*" ? "dsh-user" : String(connection.userId),
1525
- session_id: null
1526
- }] },
1527
- signal
1528
- }), "items", "results").map(jsonObject).find((item) => item !== void 0);
1529
- return {
1530
- action: "stored",
1531
- provider: this.id,
1532
- summary: "Honcho stored an explicit peer conclusion.",
1533
- ...jsonString(created?.id) === void 0 ? {} : { id: jsonString(created?.id) }
1534
- };
1535
- }
1536
- async forget(body, id, signal) {
1537
- const connection = this.connection(body);
1538
- await this.request(body, `${this.basePath(connection)}/conclusions/${encodeURIComponent(id)}`, {
1539
- method: "DELETE",
1540
- headers: this.headers(connection),
1541
- signal
1542
- });
1543
- return {
1544
- action: "deleted",
1545
- provider: this.id,
1546
- id
1547
- };
1548
- }
1549
- basePath(connection) {
1550
- return `/v3/workspaces/${encodeURIComponent(String(connection.workspace))}`;
1551
- }
1552
- scope(connection, requirePeers = false) {
1553
- const agentId = String(connection.agentId);
1554
- const userId = String(connection.userId);
1555
- return {
1556
- ...agentId === "*" ? requirePeers ? { observer_id: "dsh" } : {} : { observer_id: agentId },
1557
- ...userId === "*" ? requirePeers ? { observed_id: "dsh-user" } : {} : { observed_id: userId }
1558
- };
1559
- }
1560
- headers(connection) {
1561
- const token = String(connection.apiKey ?? "").replace(/^Bearer\s+/iu, "");
1562
- return token === "" ? {} : { Authorization: `Bearer ${token}` };
1563
- }
1564
- };
1565
- //#endregion
1566
- //#region src/providers/mem0.ts
1567
- function category(item) {
1568
- const categories = jsonArray(item.categories).filter((value) => typeof value === "string");
1569
- return jsonString(item.category) ?? categories[0] ?? "general";
1570
- }
1571
- function insight$2(value) {
1572
- const item = jsonObject(value);
1573
- const id = jsonString(item?.id);
1574
- const content = jsonString(item?.memory) ?? jsonString(item?.text) ?? jsonString(item?.content);
1575
- if (id === void 0 || content === void 0) return void 0;
1576
- const score = jsonNumber(item?.score);
1577
- const createdAt = jsonString(item?.created_at) ?? jsonString(item?.createdAt) ?? jsonString(item?.updated_at);
1578
- const tags = jsonArray(item?.categories).filter((entry) => typeof entry === "string");
1579
- return {
1580
- id,
1581
- content,
1582
- category: category(item),
1583
- source: "external",
1584
- ...score === void 0 ? {} : { score },
1585
- ...createdAt === void 0 ? {} : { createdAt },
1586
- ...tags.length === 0 ? {} : { tags }
1587
- };
1588
- }
1589
- var Mem0Provider = class extends HttpMemoryProvider {
1590
- id = "mem0";
1591
- scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
1592
- constructor(memoryBodies, options = {}) {
1593
- super(memoryBodies, options);
1594
- }
1595
- async discover(connection, signal) {
1596
- const mode = String(connection.mode ?? "platform");
1597
- return firstArray(await this.requestConnection(connection, mode === "self-hosted" ? "/entities" : "/v1/entities", {
1598
- headers: this.headers(connection, mode),
1599
- signal
1600
- }), "entities", "results").flatMap((value) => {
1601
- const item = jsonObject(value);
1602
- const id = jsonString(item?.id);
1603
- const type = jsonString(item?.type);
1604
- if (id === void 0 || type !== "user" && type !== "agent") return [];
1605
- const metadata = jsonObject(item?.metadata);
1606
- const count = jsonNumber(item?.total_memories);
1607
- return [{
1608
- externalId: `${type}:${id}`,
1609
- name: jsonString(item?.name) ?? jsonString(metadata?.name) ?? id,
1610
- description: jsonString(metadata?.description) ?? `${type === "user" ? "User" : "Agent"} memory${count === void 0 ? "" : ` · ${count} memories`}`,
1611
- connection: type === "user" ? {
1612
- userId: id,
1613
- agentId: "*",
1614
- rerank: false
1615
- } : {
1616
- userId: "*",
1617
- agentId: id,
1618
- rerank: false
1619
- }
1620
- }];
1621
- });
1622
- }
1623
- async status(body, signal) {
1624
- try {
1625
- await this.list(body, { limit: 1 }, signal);
1626
- return { healthy: true };
1627
- } catch (error) {
1628
- return {
1629
- healthy: false,
1630
- error: error instanceof Error ? error.message : String(error)
1631
- };
1632
- }
1633
- }
1634
- async search(body, request, signal) {
1635
- const connection = this.connection(body);
1636
- const mode = String(connection.mode ?? "platform");
1637
- const filters = this.filters(connection);
1638
- return { results: firstArray(await this.request(body, mode === "self-hosted" ? "/search" : "/v3/memories/search/", {
1639
- headers: this.headers(connection, mode),
1640
- json: {
1641
- query: request.query,
1642
- filters,
1643
- top_k: request.limit ?? 10,
1644
- ...mode === "platform" && connection.rerank === true ? { rerank: true } : {}
1645
- },
1646
- signal
1647
- }), "results", "memories").map(insight$2).filter((item) => item !== void 0) };
1648
- }
1649
- async list(body, request, signal) {
1650
- const connection = this.connection(body);
1651
- const mode = String(connection.mode ?? "platform");
1652
- const limit = Math.min(Math.max(request.limit ?? 200, 1), 200);
1653
- return firstArray(mode === "self-hosted" ? await this.request(body, `/memories?${new URLSearchParams({
1654
- ...this.filters(connection),
1655
- limit: String(limit)
1656
- })}`, {
1657
- headers: this.headers(connection, mode),
1658
- signal
1659
- }) : await this.request(body, `/v3/memories/?page=1&page_size=${limit}`, {
1660
- headers: this.headers(connection, mode),
1661
- json: {
1662
- filters: this.filters(connection),
1663
- ...request.category === void 0 ? {} : { categories: [request.category] }
1664
- },
1665
- signal
1666
- }), "results", "memories").map(insight$2).filter((item) => item !== void 0);
1667
- }
1668
- async remember(body, request, signal) {
1669
- const connection = this.connection(body);
1670
- const mode = String(connection.mode ?? "platform");
1671
- const result = jsonObject(await this.request(body, mode === "self-hosted" ? "/memories" : "/v3/memories/add/", {
1672
- headers: this.headers(connection, mode),
1673
- json: {
1674
- messages: [{
1675
- role: "user",
1676
- content: request.content
1677
- }],
1678
- user_id: String(connection.userId) === "*" ? "dsh-user" : String(connection.userId),
1679
- agent_id: String(connection.agentId) === "*" ? "dsh" : String(connection.agentId),
1680
- ...mode === "self-hosted" ? { infer: false } : {},
1681
- metadata: {
1682
- source: "dsh-mnemon",
1683
- ...request.category === void 0 ? {} : { category: request.category },
1684
- ...request.importance === void 0 ? {} : { importance: request.importance },
1685
- ...request.tags === void 0 ? {} : { tags: request.tags },
1686
- ...request.entities === void 0 ? {} : { entities: request.entities }
1687
- }
1688
- },
1689
- signal
1690
- })) ?? {};
1691
- return {
1692
- action: "stored",
1693
- provider: this.id,
1694
- summary: mode === "platform" ? "Mem0 queued the memory for extraction." : "Mem0 stored the explicit memory.",
1695
- ...jsonString(result.event_id) === void 0 ? {} : { eventId: jsonString(result.event_id) },
1696
- ...jsonString(result.status) === void 0 ? {} : { status: jsonString(result.status) }
1697
- };
1698
- }
1699
- async forget(body, id, signal) {
1700
- const connection = this.connection(body);
1701
- const mode = String(connection.mode ?? "platform");
1702
- const path = mode === "self-hosted" ? `/memories/${encodeURIComponent(id)}` : `/v1/memories/${encodeURIComponent(id)}`;
1703
- await this.request(body, path, {
1704
- method: "DELETE",
1705
- headers: this.headers(connection, mode),
1706
- signal
1707
- });
1708
- return {
1709
- action: "deleted",
1710
- provider: this.id,
1711
- id
1712
- };
1713
- }
1714
- filters(connection) {
1715
- const userId = String(connection.userId);
1716
- const agentId = String(connection.agentId ?? "");
1717
- return {
1718
- ...userId === "*" ? {} : { user_id: userId },
1719
- ...agentId === "" || agentId === "*" ? {} : { agent_id: agentId }
1720
- };
1721
- }
1722
- headers(connection, mode) {
1723
- const apiKey = String(connection.apiKey ?? "").replace(/^(?:Token|Bearer)\s+/iu, "");
1724
- if (apiKey === "") return {};
1725
- return mode === "self-hosted" ? { "X-API-Key": apiKey } : { Authorization: `Token ${apiKey}` };
1726
- }
1727
- };
1728
- //#endregion
1729
- //#region src/providers/openviking.ts
1730
- function object(value) {
1731
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1732
- }
1733
- function string(value) {
1734
- return typeof value === "string" ? value : void 0;
1735
- }
1736
- function number(value) {
1737
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
1738
- }
1739
- function delay(ms, signal) {
1740
- if (signal?.aborted === true) return Promise.reject(signal.reason ?? /* @__PURE__ */ new Error("OpenViking request aborted"));
1741
- return new Promise((resolve, reject) => {
1742
- const aborted = () => {
1743
- clearTimeout(timer);
1744
- reject(signal?.reason ?? /* @__PURE__ */ new Error("OpenViking request aborted"));
1745
- };
1746
- const timer = setTimeout(() => {
1747
- signal?.removeEventListener("abort", aborted);
1748
- resolve();
1749
- }, ms);
1750
- signal?.addEventListener("abort", aborted, { once: true });
1751
- });
1752
- }
1753
- function categoryFromUri(uri) {
1754
- const marker = "/memories/";
1755
- return (uri.includes(marker) ? uri.slice(uri.indexOf(marker) + 10) : "").split("/")[0]?.replace(/\.md$/u, "") || "general";
1756
- }
1757
- var OpenVikingProvider = class {
1758
- memoryBodies;
1759
- id = "openviking";
1760
- scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
1761
- requestFetch;
1762
- requestTimeoutMs;
1763
- settlementTimeoutMs;
1764
- pollIntervalMs;
1765
- constructor(memoryBodies, options = {}) {
1766
- this.memoryBodies = memoryBodies;
1767
- this.requestFetch = options.fetch ?? globalThis.fetch;
1768
- this.requestTimeoutMs = options.requestTimeoutMs ?? 15e3;
1769
- this.settlementTimeoutMs = options.settlementTimeoutMs ?? 12e4;
1770
- this.pollIntervalMs = options.pollIntervalMs ?? 750;
1771
- }
1772
- async discover(connection, signal) {
1773
- let account = String(connection.account ?? "").trim();
1774
- if (account === "") {
1775
- const accounts = await this.requestConnection(connection, "/api/v1/admin/accounts", {}, { signal });
1776
- const ids = (Array.isArray(accounts) ? accounts : []).flatMap((value) => {
1777
- const id = string(object(value)?.account_id) ?? string(object(value)?.id);
1778
- return id === void 0 ? [] : [id];
1779
- });
1780
- if (ids.length > 1) throw new Error("OpenViking exposes multiple accounts; configure the account to select one discovery scope");
1781
- account = ids[0] ?? "default";
1782
- }
1783
- const users = await this.requestConnection({
1784
- ...connection,
1785
- account
1786
- }, `/api/v1/admin/accounts/${encodeURIComponent(account)}/users?limit=100`, {}, { signal });
1787
- return (Array.isArray(users) ? users : []).flatMap((value) => {
1788
- const item = object(value);
1789
- const user = string(item?.user_id) ?? string(item?.id) ?? string(item?.name);
1790
- if (user === void 0) return [];
1791
- return [{
1792
- externalId: `${account}:${user}`,
1793
- name: string(item?.display_name) ?? string(item?.name) ?? user,
1794
- description: string(item?.description) ?? string(item?.role) ?? `OpenViking memory namespace for ${user}`,
1795
- connection: {
1796
- targetUri: "viking://user/memories",
1797
- user,
1798
- actorPeerId: "dsh"
1799
- }
1800
- }];
1801
- });
1802
- }
1803
- async status(body, signal) {
1804
- try {
1805
- await this.request(body, "/health", {}, {
1806
- signal,
1807
- timeoutMs: 5e3
1808
- });
1809
- return { healthy: true };
1810
- } catch (error) {
1811
- return {
1812
- healthy: false,
1813
- error: error instanceof Error ? error.message : String(error)
1814
- };
1815
- }
1816
- }
1817
- async search(body, request, signal) {
1818
- const connection = this.connection(body);
1819
- const root = object(await this.request(body, "/api/v1/search/find", {
1820
- method: "POST",
1821
- body: JSON.stringify({
1822
- query: request.query,
1823
- target_uri: connection.targetUri,
1824
- context_type: ["memory"],
1825
- limit: request.limit
1826
- })
1827
- }, { signal }));
1828
- return { results: (Array.isArray(root?.memories) ? root.memories : []).flatMap((value) => {
1829
- const item = object(value);
1830
- const uri = string(item?.uri);
1831
- if (uri === void 0) return [];
1832
- const score = number(item?.score);
1833
- return [{
1834
- id: uri,
1835
- externalUri: uri,
1836
- content: string(item?.overview) ?? string(item?.abstract) ?? uri,
1837
- category: string(item?.category) ?? categoryFromUri(uri),
1838
- source: "external",
1839
- ...score === void 0 ? {} : { score }
1840
- }];
1841
- }) };
1842
- }
1843
- async graph(body, signal) {
1844
- return {
1845
- nodes: (await this.list(body, { limit: 200 }, signal)).map((item) => ({
1846
- ...item,
1847
- color: "#5568d9"
1848
- })),
1849
- edges: [],
1850
- generatedAt: (/* @__PURE__ */ new Date()).toISOString()
1851
- };
1852
- }
1853
- async list(body, request, signal) {
1854
- const connection = this.connection(body);
1855
- const query = new URLSearchParams({
1856
- uri: connection.targetUri,
1857
- recursive: "true",
1858
- output: "original"
1859
- });
1860
- const result = await this.request(body, `/api/v1/fs/ls?${query}`, {}, { signal });
1861
- const entries = Array.isArray(result) ? result : [];
1862
- const limit = Math.min(Math.max(request.limit ?? 200, 1), 1e3);
1863
- const files = entries.flatMap((value) => {
1864
- const item = object(value);
1865
- const uri = string(item?.uri);
1866
- const filename = uri?.slice(uri.lastIndexOf("/") + 1);
1867
- return item === void 0 || uri === void 0 || item.isDir === true || filename?.startsWith(".") === true || !uri.endsWith(".md") ? [] : [{
1868
- item,
1869
- uri
1870
- }];
1871
- }).slice(0, limit);
1872
- return Promise.all(files.map(async ({ item, uri }) => {
1873
- let content = string(item.abstract) ?? string(item.overview) ?? "";
1874
- if (content === "") try {
1875
- const read = await this.request(body, `/api/v1/content/abstract?uri=${encodeURIComponent(uri)}`, {}, { signal });
1876
- content = string(read) ?? string(object(read)?.content) ?? string(object(read)?.abstract) ?? uri;
1877
- } catch {
1878
- content = uri;
1879
- }
1880
- const createdAt = string(item.modTime);
1881
- return {
1882
- id: uri,
1883
- externalUri: uri,
1884
- content,
1885
- category: categoryFromUri(uri),
1886
- source: "external",
1887
- ...createdAt === void 0 ? {} : { createdAt }
1888
- };
1889
- }));
1890
- }
1891
- async remember(body, request, signal) {
1892
- const sessionId = `dsh-mnemon-${Date.now()}-${randomUUID()}`;
1893
- await this.request(body, "/api/v1/sessions", {
1894
- method: "POST",
1895
- body: JSON.stringify({ session_id: sessionId })
1896
- }, { signal });
1897
- await this.request(body, `/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, {
1898
- method: "POST",
1899
- body: JSON.stringify({
1900
- role: "user",
1901
- content: request.content
1902
- })
1903
- }, { signal });
1904
- const committed = object(await this.request(body, `/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`, {
1905
- method: "POST",
1906
- body: JSON.stringify({ keep_recent_count: 0 })
1907
- }, {
1908
- signal,
1909
- timeoutMs: 3e4
1910
- }));
1911
- const taskId = string(committed?.task_id);
1912
- const archiveUri = string(committed?.archive_uri);
1913
- if (taskId === void 0) return {
1914
- action: "skipped",
1915
- provider: "openviking",
1916
- summary: string(committed?.reason) ?? "OpenViking did not archive a memory candidate.",
1917
- sessionId
1918
- };
1919
- const task = await this.settleTask(body, taskId, signal);
1920
- if (task === void 0) return {
1921
- action: "queued",
1922
- provider: "openviking",
1923
- summary: "OpenViking accepted the session and is extracting durable memories asynchronously.",
1924
- status: "pending",
1925
- taskId,
1926
- sessionId,
1927
- ...archiveUri === void 0 ? {} : { archiveUri }
1928
- };
1929
- const extracted = object(object(task.result)?.memories_extracted) ?? {};
1930
- const total = Object.values(extracted).reduce((sum, value) => sum + (number(value) ?? 0), 0);
1931
- return {
1932
- action: total > 0 ? "stored" : "skipped",
1933
- provider: "openviking",
1934
- summary: total > 0 ? `OpenViking extracted ${total} durable ${total === 1 ? "memory" : "memories"}.` : "OpenViking completed extraction without a durable memory change.",
1935
- taskId,
1936
- sessionId,
1937
- ...archiveUri === void 0 ? {} : { archiveUri },
1938
- extracted
1939
- };
1940
- }
1941
- async forget(body, id, signal) {
1942
- const connection = this.connection(body);
1943
- const uri = id.trim();
1944
- const root = connection.targetUri.replace(/\/+$/u, "");
1945
- const filename = uri.slice(uri.lastIndexOf("/") + 1);
1946
- if (!uri.startsWith(`${root}/`) || !uri.endsWith(".md") || filename.startsWith(".")) throw new Error("OpenViking forget requires an exact non-generated .md memory URI inside this Memory Space");
1947
- const query = new URLSearchParams({
1948
- uri,
1949
- recursive: "false"
1950
- });
1951
- const result = object(await this.request(body, `/api/v1/fs?${query}`, { method: "DELETE" }, { signal })) ?? {};
1952
- return {
1953
- action: "deleted",
1954
- provider: this.id,
1955
- uri: string(result.uri) ?? uri,
1956
- ...number(result.estimated_deleted_count) === void 0 ? {} : { estimatedDeletedCount: number(result.estimated_deleted_count) }
1957
- };
1958
- }
1959
- connection(body) {
1960
- if (body.provider.id !== this.id) throw new Error(`OpenViking cannot serve provider ${body.provider.id}`);
1961
- return this.memoryBodies.openVikingConnection(body.id);
1962
- }
1963
- async settleTask(body, taskId, signal) {
1964
- const deadline = Date.now() + this.settlementTimeoutMs;
1965
- while (Date.now() < deadline) {
1966
- const task = object(await this.request(body, `/api/v1/tasks/${encodeURIComponent(taskId)}`, {}, {
1967
- signal,
1968
- timeoutMs: 1e4
1969
- })) ?? {};
1970
- const status = string(task.status);
1971
- if (status === "completed") return task;
1972
- if (status === "failed" || status === "cancelled") throw new Error(`OpenViking memory extraction ${status}: ${string(task.error) ?? taskId}`);
1973
- await delay(this.pollIntervalMs, signal);
1974
- }
1975
- }
1976
- async request(body, path, init = {}, options = {}) {
1977
- const connection = this.connection(body);
1978
- return this.requestConnection(connection, path, init, options);
1979
- }
1980
- async requestConnection(connection, path, init = {}, options = {}) {
1981
- options.signal?.throwIfAborted();
1982
- const controller = new AbortController();
1983
- const relay = () => controller.abort(options.signal?.reason);
1984
- options.signal?.addEventListener("abort", relay, { once: true });
1985
- const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("OpenViking request timed out")), options.timeoutMs ?? this.requestTimeoutMs);
1986
- try {
1987
- const response = await this.requestFetch(`${connection.endpoint}${path}`, {
1988
- ...init,
1989
- headers: {
1990
- "Content-Type": "application/json",
1991
- ...connection.apiKey === void 0 || connection.apiKey === "" ? {} : { Authorization: `Bearer ${connection.apiKey}` },
1992
- ...connection.account === void 0 || connection.account === "" ? {} : { "X-OpenViking-Account": String(connection.account) },
1993
- ...connection.user === void 0 || connection.user === "" ? {} : { "X-OpenViking-User": String(connection.user) },
1994
- ...connection.actorPeerId === void 0 || connection.actorPeerId === "" ? {} : { "X-OpenViking-Actor-Peer": String(connection.actorPeerId) },
1995
- ...init.headers
1996
- },
1997
- signal: controller.signal
1998
- });
1999
- const envelope = await response.json().catch(() => ({}));
2000
- if (!response.ok || envelope.status === "error") {
2001
- const trace = envelope.error?.trace_id ?? envelope.trace_id;
2002
- throw new Error(`${envelope.error?.message ?? `OpenViking HTTP ${response.status}`}${trace === void 0 ? "" : ` (trace ${trace})`}`);
2003
- }
2004
- return envelope.result ?? envelope;
2005
- } catch (error) {
2006
- if (controller.signal.aborted && options.signal?.aborted !== true) throw new Error(`OpenViking request timed out after ${options.timeoutMs ?? this.requestTimeoutMs}ms`);
2007
- throw error;
2008
- } finally {
2009
- clearTimeout(timer);
2010
- options.signal?.removeEventListener("abort", relay);
2011
- }
2012
- }
2013
- };
2014
- //#endregion
2015
- //#region src/providers/retaindb.ts
2016
- function insight$1(value) {
2017
- const item = jsonObject(value);
2018
- const id = jsonString(item?.id) ?? jsonString(item?.memory_id);
2019
- const content = jsonString(item?.content) ?? jsonString(item?.memory) ?? jsonString(item?.text);
2020
- if (id === void 0 || content === void 0) return void 0;
2021
- const score = jsonNumber(item?.score) ?? jsonNumber(item?.similarity);
2022
- const createdAt = jsonString(item?.created_at) ?? jsonString(item?.createdAt) ?? jsonString(item?.updated_at);
2023
- return {
2024
- id,
2025
- content,
2026
- category: jsonString(item?.memory_type) ?? jsonString(item?.category) ?? "general",
2027
- source: "external",
2028
- ...score === void 0 ? {} : { score },
2029
- ...createdAt === void 0 ? {} : { createdAt }
2030
- };
2031
- }
2032
- var RetainDbProvider = class extends HttpMemoryProvider {
2033
- id = "retaindb";
2034
- scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
2035
- constructor(memoryBodies, options = {}) {
2036
- super(memoryBodies, options);
2037
- }
2038
- async discover(connection, signal) {
2039
- return firstArray(await this.requestConnection(connection, "/v1/projects", {
2040
- headers: this.headers(connection, "/v1/projects"),
2041
- signal
2042
- }), "projects", "items").flatMap((value) => {
2043
- const item = jsonObject(value);
2044
- const project = jsonString(item?.slug) ?? jsonString(item?.name) ?? jsonString(item?.id);
2045
- if (project === void 0) return [];
2046
- return [{
2047
- externalId: jsonString(item?.id) ?? project,
2048
- name: jsonString(item?.name) ?? project,
2049
- description: jsonString(item?.description) ?? `RetainDB project ${project}`,
2050
- connection: {
2051
- project,
2052
- userId: "*"
2053
- }
2054
- }];
2055
- });
2056
- }
2057
- async status(body, signal) {
2058
- try {
2059
- await this.list(body, { limit: 1 }, signal);
2060
- return { healthy: true };
2061
- } catch (error) {
2062
- return {
2063
- healthy: false,
2064
- error: error instanceof Error ? error.message : String(error)
2065
- };
2066
- }
2067
- }
2068
- async search(body, request, signal) {
2069
- const connection = this.connection(body);
2070
- return { results: firstArray(await this.request(body, "/v1/memory/search", {
2071
- headers: this.headers(connection, "/v1/memory/search"),
2072
- json: {
2073
- project: String(connection.project),
2074
- query: request.query,
2075
- ...String(connection.userId) === "*" ? {} : { user_id: String(connection.userId) },
2076
- session_id: `dsh-${body.id}`,
2077
- top_k: request.limit ?? 10,
2078
- include_pending: true
2079
- },
2080
- signal
2081
- }), "results", "memories").map(insight$1).filter((item) => item !== void 0) };
2082
- }
2083
- async list(body, request, signal) {
2084
- const connection = this.connection(body);
2085
- const params = new URLSearchParams({
2086
- project: String(connection.project),
2087
- include_pending: "true"
2088
- });
2089
- let payload;
2090
- try {
2091
- if (String(connection.userId) === "*") throw new Error("project-wide scope uses the collection endpoint");
2092
- payload = await this.request(body, `/v1/memory/profile/${encodeURIComponent(String(connection.userId))}?${params}`, {
2093
- headers: this.headers(connection, "/v1/memory/profile"),
2094
- signal
2095
- });
2096
- } catch {
2097
- if (String(connection.userId) !== "*") params.set("user_id", String(connection.userId));
2098
- params.set("limit", String(Math.min(Math.max(request.limit ?? 200, 1), 200)));
2099
- payload = await this.request(body, `/v1/memories?${params}`, {
2100
- headers: this.headers(connection, "/v1/memories"),
2101
- signal
2102
- });
2103
- }
2104
- return firstArray(payload, "memories", "results").map(insight$1).filter((item) => item !== void 0).filter((item) => request.category === void 0 || item.category === request.category).slice(0, Math.min(Math.max(request.limit ?? 200, 1), 200));
2105
- }
2106
- async remember(body, request, signal) {
2107
- const connection = this.connection(body);
2108
- const json = {
2109
- project: String(connection.project),
2110
- content: request.content,
2111
- memory_type: request.category ?? "factual",
2112
- user_id: String(connection.userId) === "*" ? "dsh-user" : String(connection.userId),
2113
- session_id: `dsh-${body.id}`,
2114
- importance: request.importance ?? .7,
2115
- write_mode: "sync"
2116
- };
2117
- let payload;
2118
- try {
2119
- payload = await this.request(body, "/v1/memory", {
2120
- headers: this.headers(connection, "/v1/memory"),
2121
- json,
2122
- signal
2123
- });
2124
- } catch {
2125
- const { write_mode: _writeMode, ...legacy } = json;
2126
- payload = await this.request(body, "/v1/memories", {
2127
- headers: this.headers(connection, "/v1/memories"),
2128
- json: legacy,
2129
- signal
2130
- });
2131
- }
2132
- const result = jsonObject(payload) ?? {};
2133
- return {
2134
- action: "stored",
2135
- provider: this.id,
2136
- summary: "RetainDB stored the memory synchronously.",
2137
- ...jsonString(result.id) === void 0 ? {} : { id: jsonString(result.id) }
2138
- };
2139
- }
2140
- async forget(body, id, signal) {
2141
- const connection = this.connection(body);
2142
- try {
2143
- await this.request(body, `/v1/memory/${encodeURIComponent(id)}`, {
2144
- method: "DELETE",
2145
- headers: this.headers(connection, "/v1/memory"),
2146
- signal
2147
- });
2148
- } catch {
2149
- await this.request(body, `/v1/memories/${encodeURIComponent(id)}`, {
2150
- method: "DELETE",
2151
- headers: this.headers(connection, "/v1/memories"),
2152
- signal
2153
- });
2154
- }
2155
- return {
2156
- action: "deleted",
2157
- provider: this.id,
2158
- id
2159
- };
2160
- }
2161
- headers(connection, path) {
2162
- const token = String(connection.apiKey ?? "").replace(/^Bearer\s+/iu, "");
2163
- return {
2164
- Authorization: `Bearer ${token}`,
2165
- "x-sdk-runtime": "dsh-mnemon",
2166
- ...path.startsWith("/v1/memory") || path.startsWith("/v1/context") ? { "X-API-Key": token } : {}
2167
- };
2168
- }
2169
- };
2170
- //#endregion
2171
- //#region src/providers/supermemory.ts
2172
- function insight(value) {
2173
- const item = jsonObject(value);
2174
- const id = jsonString(item?.id);
2175
- const content = jsonString(item?.memory) ?? jsonString(item?.chunk) ?? jsonString(item?.content);
2176
- if (id === void 0 || content === void 0) return void 0;
2177
- const metadata = jsonObject(item?.metadata);
2178
- const score = jsonNumber(item?.similarity) ?? jsonNumber(item?.score);
2179
- const createdAt = jsonString(item?.updatedAt) ?? jsonString(item?.createdAt);
2180
- return {
2181
- id,
2182
- content,
2183
- category: jsonString(metadata?.category) ?? "general",
2184
- source: "external",
2185
- ...score === void 0 ? {} : { score },
2186
- ...createdAt === void 0 ? {} : { createdAt }
2187
- };
2188
- }
2189
- var SupermemoryProvider = class extends HttpMemoryProvider {
2190
- id = "supermemory";
2191
- scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
2192
- constructor(memoryBodies, options = {}) {
2193
- super(memoryBodies, options);
2194
- }
2195
- async discover(connection, signal) {
2196
- return firstArray(await this.requestConnection(connection, "/v3/container-tags/list", {
2197
- headers: this.headers(connection),
2198
- signal
2199
- }), "containerTags", "items").flatMap((value) => {
2200
- const item = jsonObject(value);
2201
- const tag = jsonString(item?.containerTag) ?? jsonString(item?.container_tag);
2202
- if (tag === void 0) return [];
2203
- return [{
2204
- externalId: jsonString(item?.id) ?? tag,
2205
- name: jsonString(item?.name) ?? tag,
2206
- description: jsonString(item?.description) ?? `Supermemory space ${tag}`,
2207
- connection: {
2208
- containerTag: tag,
2209
- searchMode: "hybrid"
2210
- }
2211
- }];
2212
- });
2213
- }
2214
- async status(body, signal) {
2215
- try {
2216
- await this.list(body, { limit: 1 }, signal);
2217
- return { healthy: true };
2218
- } catch (error) {
2219
- return {
2220
- healthy: false,
2221
- error: error instanceof Error ? error.message : String(error)
2222
- };
2223
- }
2224
- }
2225
- async search(body, request, signal) {
2226
- const connection = this.connection(body);
2227
- return { results: firstArray(await this.request(body, "/v4/search", {
2228
- headers: this.headers(connection),
2229
- json: {
2230
- q: request.query,
2231
- containerTag: String(connection.containerTag),
2232
- searchMode: String(connection.searchMode ?? "hybrid"),
2233
- limit: request.limit ?? 10
2234
- },
2235
- signal
2236
- }), "results").map(insight).filter((item) => item !== void 0) };
2237
- }
2238
- async list(body, request, signal) {
2239
- const connection = this.connection(body);
2240
- const limit = Math.min(Math.max(request.limit ?? 200, 1), 200);
2241
- const memories = firstArray(await this.request(body, "/v4/memories/list", {
2242
- headers: this.headers(connection),
2243
- json: {
2244
- containerTags: [String(connection.containerTag)],
2245
- limit,
2246
- page: 1,
2247
- sort: "createdAt",
2248
- order: "desc"
2249
- },
2250
- signal
2251
- }), "memoryEntries", "results").map(insight).filter((item) => item !== void 0);
2252
- const projectedDocuments = firstArray(await this.request(body, "/v3/documents/documents", {
2253
- headers: this.headers(connection),
2254
- json: {
2255
- containerTags: [String(connection.containerTag)],
2256
- limit,
2257
- page: 1,
2258
- sort: "createdAt",
2259
- order: "desc"
2260
- },
2261
- signal
2262
- }), "documents", "memories", "results").map(insight).filter((item) => item !== void 0);
2263
- return [...new Map([...memories, ...projectedDocuments].map((item) => [item.id, item])).values()].filter((item) => request.category === void 0 || item.category === request.category).slice(0, limit);
2264
- }
2265
- async remember(body, request, signal) {
2266
- const connection = this.connection(body);
2267
- const result = jsonObject(await this.request(body, "/v3/documents", {
2268
- headers: this.headers(connection),
2269
- json: {
2270
- content: request.content,
2271
- containerTag: String(connection.containerTag),
2272
- taskType: "memory",
2273
- metadata: {
2274
- sm_source: "dsh-mnemon",
2275
- ...request.category === void 0 ? {} : { category: request.category },
2276
- ...request.importance === void 0 ? {} : { importance: request.importance }
2277
- }
2278
- },
2279
- signal
2280
- })) ?? {};
2281
- return {
2282
- action: "stored",
2283
- provider: this.id,
2284
- summary: "Supermemory accepted the memory document for extraction.",
2285
- ...jsonString(result.id) === void 0 ? {} : { id: jsonString(result.id) },
2286
- ...jsonString(result.status) === void 0 ? {} : { status: jsonString(result.status) }
2287
- };
2288
- }
2289
- async forget(body, id, signal) {
2290
- const connection = this.connection(body);
2291
- try {
2292
- const payload = await this.request(body, "/v4/memories", {
2293
- method: "DELETE",
2294
- headers: this.headers(connection),
2295
- json: {
2296
- id,
2297
- containerTag: String(connection.containerTag),
2298
- reason: "Deleted from dsh-mnemon"
2299
- },
2300
- signal
2301
- });
2302
- return {
2303
- action: "deleted",
2304
- provider: this.id,
2305
- id,
2306
- ...jsonObject(payload)?.forgotten === void 0 ? {} : { forgotten: jsonObject(payload).forgotten }
2307
- };
2308
- } catch (error) {
2309
- if (!(error instanceof Error) || !/HTTP 404\b/u.test(error.message)) throw error;
2310
- await this.request(body, `/v3/documents/${encodeURIComponent(id)}`, {
2311
- method: "DELETE",
2312
- headers: this.headers(connection),
2313
- signal
2314
- });
2315
- return {
2316
- action: "deleted",
2317
- provider: this.id,
2318
- id,
2319
- document: true
2320
- };
2321
- }
2322
- }
2323
- headers(connection) {
2324
- return {
2325
- Authorization: `Bearer ${String(connection.apiKey ?? "").replace(/^Bearer\s+/iu, "")}`,
2326
- "x-sm-source": "dsh-mnemon"
2327
- };
2328
- }
2329
- };
2330
- //#endregion
2331
- //#region packages/provider-sdk/src/index.ts
2332
- /** Lifecycle-owned factory directory used by Provider plugins and the Host. */
2333
- var MemoryAdapterFactoryRegistry = class {
2334
- factories = /* @__PURE__ */ new Map();
2335
- constructor(factories = []) {
2336
- for (const factory of factories) this.register(factory);
2337
- }
2338
- register(factory) {
2339
- if (this.factories.has(factory.id)) throw new Error(`memory adapter factory is already registered: ${factory.id}`);
2340
- this.factories.set(factory.id, factory);
2341
- let active = true;
2342
- return () => {
2343
- if (!active) return;
2344
- active = false;
2345
- if (this.factories.get(factory.id) === factory) this.factories.delete(factory.id);
2346
- };
2347
- }
2348
- create(context) {
2349
- const adapters = /* @__PURE__ */ new Map();
2350
- for (const factory of this.factories.values()) {
2351
- const adapter = factory.create(context);
2352
- if (adapter.id !== factory.id) throw new Error(`memory adapter factory ${factory.id} returned ${adapter.id}`);
2353
- if (adapters.has(adapter.id)) throw new Error(`memory adapter is already created: ${adapter.id}`);
2354
- adapters.set(adapter.id, adapter);
2355
- }
2356
- return adapters;
2357
- }
2358
- ids() {
2359
- return [...this.factories.keys()];
2360
- }
2361
- };
2362
- function defineMemoryAdapterDescriptor(descriptor) {
2363
- return descriptor;
2364
- }
2365
- //#endregion
2366
- //#region src/providers/registry.ts
2367
- /**
2368
- * Runtime adapter factory seam. The control plane owns registration and
2369
- * provider implementations own construction; MnemonService depends only on
2370
- * the resulting adapter contract.
2371
- */
2372
- var MemoryProviderAdapterRegistry = class extends MemoryAdapterFactoryRegistry {};
2373
- const BUILTIN_MEMORY_PROVIDER_ADAPTER_FACTORIES = [
2374
- {
2375
- id: "mnemon-native",
2376
- create: (context) => context.nativeAdapter
2377
- },
2378
- {
2379
- id: "openviking",
2380
- create: (context) => new OpenVikingProvider(context.memoryBodies, {
2381
- requestTimeoutMs: context.config.timeoutMs,
2382
- settlementTimeoutMs: context.config.timeoutMs
2383
- })
2384
- },
2385
- {
2386
- id: "honcho",
2387
- create: (context) => new HonchoProvider(context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
2388
- },
2389
- {
2390
- id: "mem0",
2391
- create: (context) => new Mem0Provider(context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
2392
- },
2393
- {
2394
- id: "hindsight",
2395
- create: (context) => new HindsightProvider(context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
2396
- },
2397
- {
2398
- id: "holographic",
2399
- create: (context) => new HolographicProvider(context.memoryBodies)
2400
- },
2401
- {
2402
- id: "retaindb",
2403
- create: (context) => new RetainDbProvider(context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
2404
- },
2405
- {
2406
- id: "byterover",
2407
- create: (context) => new ByteRoverProvider(context.memoryBodies, { queryTimeoutMs: context.config.timeoutMs })
2408
- },
2409
- {
2410
- id: "supermemory",
2411
- create: (context) => new SupermemoryProvider(context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
2412
- }
2413
- ];
2414
- function createBuiltinMemoryProviderAdapterRegistry() {
2415
- return new MemoryProviderAdapterRegistry(BUILTIN_MEMORY_PROVIDER_ADAPTER_FACTORIES);
2416
- }
2417
- /** Global extension registry sampled when a runtime generation is constructed. */
2418
- const memoryProviderAdapterFactories = createBuiltinMemoryProviderAdapterRegistry();
2419
- function registerMemoryProviderAdapterFactory(factory) {
2420
- return memoryProviderAdapterFactories.register(factory);
2421
- }
2422
- //#endregion
2423
- export { publicScopedProviderConnection as _, MemoryAdapterFactoryRegistry as a, MEMORY_PROVIDER_CATALOG as c, isMemoryProviderId as d, memoryProviderDescriptor as f, publicProviderConnection as g, normalizeProviderServiceConnection as h, registerMemoryProviderAdapterFactory as i, MEMORY_PROVIDER_IDS as l, normalizeProviderMemoryConnection as m, createBuiltinMemoryProviderAdapterRegistry as n, defineMemoryAdapterDescriptor as o, normalizeProviderConnection as p, memoryProviderAdapterFactories as r, NORMALIZED_RELEVANCE_SCORE as s, MemoryProviderAdapterRegistry as t, MEMORY_PROVIDER_ID_SET as u, splitProviderConnection as v, runProcess as y };