@linxiraos/pi-mnemopi 1.0.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 (135) hide show
  1. package/CHANGELOG.md +248 -0
  2. package/README.md +108 -0
  3. package/dist/types/cli.d.ts +35 -0
  4. package/dist/types/config.d.ts +108 -0
  5. package/dist/types/core/aaak.d.ts +55 -0
  6. package/dist/types/core/annotations.d.ts +75 -0
  7. package/dist/types/core/banks.d.ts +33 -0
  8. package/dist/types/core/beam/consolidate.d.ts +38 -0
  9. package/dist/types/core/beam/helpers.d.ts +69 -0
  10. package/dist/types/core/beam/index.d.ts +59 -0
  11. package/dist/types/core/beam/recall.d.ts +52 -0
  12. package/dist/types/core/beam/schema.d.ts +2 -0
  13. package/dist/types/core/beam/store.d.ts +57 -0
  14. package/dist/types/core/beam/types.d.ts +268 -0
  15. package/dist/types/core/binary-vectors.d.ts +54 -0
  16. package/dist/types/core/chat-normalize.d.ts +13 -0
  17. package/dist/types/core/content-sanitizer.d.ts +18 -0
  18. package/dist/types/core/cost-log.d.ts +13 -0
  19. package/dist/types/core/embeddings.d.ts +93 -0
  20. package/dist/types/core/entities.d.ts +9 -0
  21. package/dist/types/core/episodic-graph.d.ts +89 -0
  22. package/dist/types/core/extraction/client.d.ts +35 -0
  23. package/dist/types/core/extraction/diagnostics.d.ts +51 -0
  24. package/dist/types/core/extraction/prompts.d.ts +2 -0
  25. package/dist/types/core/extraction.d.ts +34 -0
  26. package/dist/types/core/fastembed-model-cache.d.ts +2 -0
  27. package/dist/types/core/fastembed-runtime.d.ts +41 -0
  28. package/dist/types/core/index.d.ts +6 -0
  29. package/dist/types/core/llm-backends.d.ts +23 -0
  30. package/dist/types/core/local-llm.d.ts +20 -0
  31. package/dist/types/core/memory.d.ts +186 -0
  32. package/dist/types/core/migrations/e6-triplestore-split.d.ts +17 -0
  33. package/dist/types/core/migrations/index.d.ts +1 -0
  34. package/dist/types/core/mmr.d.ts +8 -0
  35. package/dist/types/core/orchestrator.d.ts +20 -0
  36. package/dist/types/core/patterns.d.ts +61 -0
  37. package/dist/types/core/plugins.d.ts +109 -0
  38. package/dist/types/core/polyphonic-recall.d.ts +66 -0
  39. package/dist/types/core/query-cache.d.ts +45 -0
  40. package/dist/types/core/query-intent.d.ts +20 -0
  41. package/dist/types/core/recall-diagnostics.d.ts +48 -0
  42. package/dist/types/core/runtime-options.d.ts +76 -0
  43. package/dist/types/core/shmr.d.ts +62 -0
  44. package/dist/types/core/streaming.d.ts +136 -0
  45. package/dist/types/core/synonyms.d.ts +46 -0
  46. package/dist/types/core/temporal-parser.d.ts +16 -0
  47. package/dist/types/core/token-counter.d.ts +8 -0
  48. package/dist/types/core/triples.d.ts +63 -0
  49. package/dist/types/core/typed-memory.d.ts +39 -0
  50. package/dist/types/core/vector-index.d.ts +16 -0
  51. package/dist/types/core/vector-math.d.ts +1 -0
  52. package/dist/types/core/veracity-consolidation.d.ts +60 -0
  53. package/dist/types/core/weibull.d.ts +96 -0
  54. package/dist/types/db.d.ts +18 -0
  55. package/dist/types/diagnose.d.ts +24 -0
  56. package/dist/types/dr/index.d.ts +1 -0
  57. package/dist/types/dr/recovery.d.ts +68 -0
  58. package/dist/types/index.d.ts +6 -0
  59. package/dist/types/mcp-server.d.ts +40 -0
  60. package/dist/types/mcp-tools.d.ts +484 -0
  61. package/dist/types/migrations/e6-triplestore-split.d.ts +1 -0
  62. package/dist/types/migrations/index.d.ts +1 -0
  63. package/dist/types/types.d.ts +145 -0
  64. package/dist/types/util/datetime.d.ts +8 -0
  65. package/dist/types/util/env.d.ts +10 -0
  66. package/dist/types/util/ids.d.ts +3 -0
  67. package/dist/types/util/lru.d.ts +12 -0
  68. package/dist/types/util/regex.d.ts +11 -0
  69. package/package.json +108 -0
  70. package/src/cli.ts +398 -0
  71. package/src/config.ts +373 -0
  72. package/src/core/aaak.ts +142 -0
  73. package/src/core/annotations.ts +456 -0
  74. package/src/core/banks.ts +133 -0
  75. package/src/core/beam/consolidate.ts +1132 -0
  76. package/src/core/beam/helpers.ts +831 -0
  77. package/src/core/beam/index.ts +358 -0
  78. package/src/core/beam/recall.ts +1225 -0
  79. package/src/core/beam/schema.ts +426 -0
  80. package/src/core/beam/store.ts +1083 -0
  81. package/src/core/beam/types.ts +303 -0
  82. package/src/core/binary-vectors.ts +317 -0
  83. package/src/core/chat-normalize.ts +160 -0
  84. package/src/core/content-sanitizer.ts +136 -0
  85. package/src/core/cost-log.ts +101 -0
  86. package/src/core/embeddings.ts +624 -0
  87. package/src/core/entities.ts +263 -0
  88. package/src/core/episodic-graph.ts +708 -0
  89. package/src/core/extraction/client.ts +187 -0
  90. package/src/core/extraction/diagnostics.ts +193 -0
  91. package/src/core/extraction/prompts.ts +31 -0
  92. package/src/core/extraction.ts +491 -0
  93. package/src/core/fastembed-model-cache.ts +39 -0
  94. package/src/core/fastembed-runtime.ts +172 -0
  95. package/src/core/index.ts +39 -0
  96. package/src/core/llm-backends.ts +54 -0
  97. package/src/core/local-llm.ts +475 -0
  98. package/src/core/memory.ts +680 -0
  99. package/src/core/migrations/e6-triplestore-split.ts +211 -0
  100. package/src/core/migrations/index.ts +1 -0
  101. package/src/core/mmr.ts +101 -0
  102. package/src/core/orchestrator.ts +62 -0
  103. package/src/core/patterns.ts +484 -0
  104. package/src/core/plugins.ts +375 -0
  105. package/src/core/polyphonic-recall.ts +563 -0
  106. package/src/core/query-cache.ts +351 -0
  107. package/src/core/query-intent.ts +139 -0
  108. package/src/core/recall-diagnostics.ts +157 -0
  109. package/src/core/runtime-options.ts +130 -0
  110. package/src/core/shmr.ts +567 -0
  111. package/src/core/streaming.ts +419 -0
  112. package/src/core/synonyms.ts +197 -0
  113. package/src/core/temporal-parser.ts +363 -0
  114. package/src/core/token-counter.ts +30 -0
  115. package/src/core/triples.ts +452 -0
  116. package/src/core/typed-memory.ts +407 -0
  117. package/src/core/vector-index.ts +83 -0
  118. package/src/core/vector-math.ts +23 -0
  119. package/src/core/veracity-consolidation.ts +477 -0
  120. package/src/core/weibull.ts +124 -0
  121. package/src/db.ts +186 -0
  122. package/src/diagnose.ts +174 -0
  123. package/src/dr/index.ts +1 -0
  124. package/src/dr/recovery.ts +405 -0
  125. package/src/index.ts +33 -0
  126. package/src/mcp-server.ts +155 -0
  127. package/src/mcp-tools.ts +970 -0
  128. package/src/migrations/e6-triplestore-split.ts +1 -0
  129. package/src/migrations/index.ts +1 -0
  130. package/src/types.ts +157 -0
  131. package/src/util/datetime.ts +69 -0
  132. package/src/util/env.ts +65 -0
  133. package/src/util/ids.ts +19 -0
  134. package/src/util/lru.ts +48 -0
  135. package/src/util/regex.ts +165 -0
@@ -0,0 +1,172 @@
1
+ import { createRequire } from "node:module";
2
+ import * as path from "node:path";
3
+ import {
4
+ ensureRuntimeInstalled,
5
+ getFastembedRuntimeDir,
6
+ installRuntimeModuleResolver,
7
+ logger,
8
+ type RuntimeInstallSpec,
9
+ resolveRuntimeModule,
10
+ } from "@linxiraos/pi-utils";
11
+ import type * as Fastembed from "fastembed";
12
+ import packageManifest from "../../package.json" with { type: "json" };
13
+
14
+ type FastembedModule = typeof Fastembed;
15
+
16
+ /** Runtime install inputs for the optional fastembed embedding stack. */
17
+ export interface FastembedRuntimeInstallPlan {
18
+ /** Cache directory key; changes when runtime resolution policy changes. */
19
+ versionKey: string;
20
+ /** Dependency graph written to the runtime cache package manifest. */
21
+ install: RuntimeInstallSpec;
22
+ }
23
+
24
+ /**
25
+ * `fastembed` is an optional peer (~270MB of native assets across platforms),
26
+ * never bundled and never installed eagerly. When the direct import cannot
27
+ * resolve — bundled `dist/cli.js`, compiled binary, a consumer that skipped the
28
+ * optional peer, or a native loader failure — fastembed is `bun install`ed into
29
+ * a per-version runtime cache on first use and loaded from there (#2389).
30
+ *
31
+ * The fastembed pin lives in `peerDependencies` as an exact version (not
32
+ * `catalog:`) so this module reads a concrete spec even when the workspace
33
+ * manifest is inlined into a bundle. The runtime install deliberately does not
34
+ * override fastembed's `onnxruntime-node` dependency: the prebuilt native addon
35
+ * links against that package's bundled ORT dylib/so/dll name.
36
+ */
37
+ const FASTEMBED_SPEC = packageManifest.peerDependencies.fastembed;
38
+
39
+ /** Build the deterministic fastembed runtime install plan used by local embeddings. */
40
+ export function fastembedRuntimeInstallPlan(): FastembedRuntimeInstallPlan {
41
+ return {
42
+ versionKey: `fastembed-${FASTEMBED_SPEC}_transitive-ort`.replace(/[^A-Za-z0-9._-]/g, "_"),
43
+ install: {
44
+ dependencies: { fastembed: FASTEMBED_SPEC },
45
+ trustedDependencies: ["onnxruntime-node"],
46
+ },
47
+ };
48
+ }
49
+ let fastembedLoad: Promise<FastembedModule> | null = null;
50
+
51
+ /** Inputs for selecting the Windows DLL directory paired with a fastembed installation. */
52
+ export interface WindowsFastembedRuntimeOptions {
53
+ /** Resolved fastembed package entry whose dependency graph owns the ORT binding. */
54
+ fastembedEntry: string;
55
+ /** Directory containing fastembed's manifest and nested dependency graph. */
56
+ fastembedPackageDir: string;
57
+ /** Native architecture to select; defaults to the current process architecture. */
58
+ arch?: string;
59
+ /** Environment receiving the DLL search path; defaults to the subprocess environment. */
60
+ env?: NodeJS.ProcessEnv;
61
+ }
62
+
63
+ /** The ORT module and DLL directory selected from fastembed's own dependency graph. */
64
+ export interface WindowsFastembedRuntime {
65
+ /** Resolved entry for fastembed's own ONNX Runtime dependency. */
66
+ ortEntry: string;
67
+ /** Package directory containing the selected ORT manifest and native assets. */
68
+ ortPackageDir: string;
69
+ /** Directory prepended to `PATH` so Windows finds the paired native DLL. */
70
+ dllDir: string;
71
+ }
72
+
73
+ /**
74
+ * Prepend the ORT DLL directory paired with fastembed before Bun loads its
75
+ * native binding. Compiled Windows binaries extract `.node` files to a
76
+ * temporary directory, so the default DLL search can otherwise select an
77
+ * unrelated `onnxruntime.dll` from the inherited system path.
78
+ */
79
+ export async function prepareWindowsFastembedRuntime({
80
+ fastembedEntry,
81
+ fastembedPackageDir,
82
+ arch = process.arch,
83
+ env = process.env,
84
+ }: WindowsFastembedRuntimeOptions): Promise<WindowsFastembedRuntime> {
85
+ const nestedNodeModules = path.join(fastembedPackageDir, "node_modules");
86
+ const rootNodeModules = path.dirname(fastembedPackageDir);
87
+ const nestedOrtEntry = resolveRuntimeModule(nestedNodeModules, "onnxruntime-node");
88
+ const ortEntry = nestedOrtEntry ?? resolveRuntimeModule(rootNodeModules, "onnxruntime-node");
89
+ const ortPackageDir = path.join(nestedOrtEntry ? nestedNodeModules : rootNodeModules, "onnxruntime-node");
90
+ if (!ortEntry) {
91
+ throw new Error(`Cannot find module onnxruntime-node beside ${fastembedEntry}`);
92
+ }
93
+ const dllGlob = new Bun.Glob(`bin/napi-*/win32/${arch}/onnxruntime.dll`);
94
+ let dllDir: string | undefined;
95
+ for await (const dll of dllGlob.scan({ cwd: ortPackageDir, absolute: true, onlyFiles: true })) {
96
+ dllDir = path.dirname(dll);
97
+ break;
98
+ }
99
+ if (!dllDir) {
100
+ throw new Error(`Cannot find module onnxruntime-node Windows DLL for ${arch} beside ${ortEntry}`);
101
+ }
102
+
103
+ const currentPath = env.PATH;
104
+ const normalizedDllDir = path.resolve(dllDir).toLowerCase();
105
+ const alreadyPresent = currentPath
106
+ ?.split(path.delimiter)
107
+ .some(entry => path.resolve(entry).toLowerCase() === normalizedDllDir);
108
+ if (!alreadyPresent) env.PATH = currentPath ? `${dllDir}${path.delimiter}${currentPath}` : dllDir;
109
+ return { ortEntry, ortPackageDir, dllDir };
110
+ }
111
+
112
+ export function loadFastembed(): Promise<FastembedModule> {
113
+ fastembedLoad ??= loadFastembedOnce().catch(error => {
114
+ fastembedLoad = null;
115
+ throw error;
116
+ });
117
+ return fastembedLoad;
118
+ }
119
+
120
+ async function loadFastembedOnce(): Promise<FastembedModule> {
121
+ try {
122
+ const requireDirect = createRequire(import.meta.url);
123
+ const manifestPath = requireDirect.resolve("fastembed/package.json");
124
+ const manifest: { version?: unknown } = requireDirect(manifestPath);
125
+ if (manifest.version !== FASTEMBED_SPEC) {
126
+ throw new Error(`Cannot find package fastembed@${FASTEMBED_SPEC}; resolved ${String(manifest.version)}`);
127
+ }
128
+ return await loadResolvedFastembed(requireDirect.resolve("fastembed"), path.dirname(manifestPath));
129
+ } catch (error) {
130
+ if (!isRecoverableFastembedLoadError(error)) throw error;
131
+ logger.debug("mnemopi: fastembed not loadable, using on-demand runtime install", {
132
+ error: String(error),
133
+ });
134
+ return loadFromRuntimeInstall();
135
+ }
136
+ }
137
+
138
+ async function loadResolvedFastembed(entry: string, fastembedPackageDir: string): Promise<FastembedModule> {
139
+ const requireFastembed = createRequire(entry);
140
+ if (process.platform === "win32") {
141
+ const { ortEntry } = await prepareWindowsFastembedRuntime({ fastembedEntry: entry, fastembedPackageDir });
142
+ requireFastembed(ortEntry);
143
+ }
144
+ const loaded: FastembedModule = requireFastembed(entry);
145
+ return loaded;
146
+ }
147
+
148
+ async function loadFromRuntimeInstall(): Promise<FastembedModule> {
149
+ const plan = fastembedRuntimeInstallPlan();
150
+ const runtimeDir = await ensureRuntimeInstalled({
151
+ runtimeDir: path.join(getFastembedRuntimeDir(), plan.versionKey),
152
+ install: plan.install,
153
+ probePackage: "fastembed",
154
+ });
155
+ const nodeModules = path.join(runtimeDir, "node_modules");
156
+ // The compiled-binary resolver ignores `main`/`exports` for real-FS bare
157
+ // specifiers (Bun #1763); route the runtime graph's requires (fastembed →
158
+ // onnxruntime-node, @anush008/tokenizers → platform binding, …) through
159
+ // the runtime cache.
160
+ installRuntimeModuleResolver({ runtimeNodeModules: nodeModules });
161
+ const entry = resolveRuntimeModule(nodeModules, "fastembed");
162
+ if (!entry) throw new Error(`fastembed runtime install at ${runtimeDir} has no loadable entry`);
163
+ return loadResolvedFastembed(entry, path.join(nodeModules, "fastembed"));
164
+ }
165
+
166
+ function isRecoverableFastembedLoadError(error: unknown): boolean {
167
+ if (typeof error !== "object" || error === null) return false;
168
+ const { name, code, message } = error as { name?: unknown; code?: unknown; message?: unknown };
169
+ if (name === "ResolveMessage") return true;
170
+ if (code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND" || code === "ERR_DLOPEN_FAILED") return true;
171
+ return typeof message === "string" && /cannot find (module|package)/i.test(message);
172
+ }
@@ -0,0 +1,39 @@
1
+ export { configureRecallFeatures, type RecallFeatureFlags } from "../config";
2
+ export * from "./banks";
3
+ export * from "./beam/index";
4
+ export {
5
+ defaultLocalModelInitializer,
6
+ type LocalEmbeddingModel,
7
+ type LocalModelInitializer,
8
+ type LocalModelInitOptions,
9
+ type StandardEmbeddingModel,
10
+ setLocalModelInitializer,
11
+ } from "./embeddings";
12
+ export * from "./memory";
13
+ export {
14
+ addMemory,
15
+ forget,
16
+ get,
17
+ getBank,
18
+ getContext,
19
+ getDefaultInstance,
20
+ getStats,
21
+ Mnemopi,
22
+ query,
23
+ recall,
24
+ recallEnhanced,
25
+ remember,
26
+ resetDefaultInstanceForTests,
27
+ resetMemoryForTests,
28
+ resetModuleStateForTests,
29
+ saveMemory,
30
+ scratchpadClear,
31
+ scratchpadRead,
32
+ scratchpadWrite,
33
+ search,
34
+ setBank,
35
+ sleep,
36
+ sleepAllSessions,
37
+ storeMemory,
38
+ update,
39
+ } from "./memory";
@@ -0,0 +1,54 @@
1
+ import type { FetchImpl } from "@linxiraos/pi-ai";
2
+
3
+ export interface CompleteOptions {
4
+ maxTokens?: number;
5
+ temperature?: number;
6
+ timeout?: number;
7
+ provider?: string | null;
8
+ model?: string | null;
9
+ fetch?: FetchImpl;
10
+ }
11
+
12
+ export interface LlmBackend {
13
+ name?: string;
14
+ complete(prompt: string, opts?: CompleteOptions): string | null | Promise<string | null>;
15
+ }
16
+
17
+ let hostBackend: LlmBackend | null = null;
18
+
19
+ export function setHostLlmBackend(backend: LlmBackend | null | undefined): void {
20
+ hostBackend = backend ?? null;
21
+ }
22
+
23
+ export function getHostLlmBackend(): LlmBackend | null {
24
+ return hostBackend;
25
+ }
26
+
27
+ export function resetHostLlmBackendForTests(): void {
28
+ hostBackend = null;
29
+ }
30
+
31
+ export async function callHostLlm(prompt: string, opts: CompleteOptions = {}): Promise<string | null> {
32
+ const backend = getHostLlmBackend();
33
+ if (backend === null) {
34
+ return null;
35
+ }
36
+
37
+ try {
38
+ const result = await backend.complete(prompt, opts);
39
+ return typeof result === "string" ? result : null;
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ export class CallableLlmBackend implements LlmBackend {
46
+ constructor(
47
+ public name: string,
48
+ private readonly fn: (prompt: string, opts?: CompleteOptions) => string | null | Promise<string | null>,
49
+ ) {}
50
+
51
+ complete(prompt: string, opts?: CompleteOptions): string | null | Promise<string | null> {
52
+ return this.fn(prompt, opts);
53
+ }
54
+ }