@objectstack/knowledge-memory 6.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +22 -0
- package/CHANGELOG.md +28 -0
- package/LICENSE +202 -0
- package/README.md +18 -0
- package/dist/index.d.mts +45 -0
- package/dist/index.d.ts +45 -0
- package/dist/index.js +182 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +156 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +37 -0
- package/src/__tests__/memory-adapter.test.ts +105 -0
- package/src/index.ts +235 -0
- package/tsconfig.json +20 -0
- package/vitest.config.ts +23 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
|
|
2
|
+
> @objectstack/knowledge-memory@6.4.0 build /home/runner/work/framework/framework/packages/plugins/knowledge-memory
|
|
3
|
+
> tsup --config ../../../tsup.config.ts
|
|
4
|
+
|
|
5
|
+
[34mCLI[39m Building entry: src/index.ts
|
|
6
|
+
[34mCLI[39m Using tsconfig: tsconfig.json
|
|
7
|
+
[34mCLI[39m tsup v8.5.1
|
|
8
|
+
[34mCLI[39m Using tsup config: /home/runner/work/framework/framework/tsup.config.ts
|
|
9
|
+
[34mCLI[39m Target: es2020
|
|
10
|
+
[34mCLI[39m Cleaning output folder
|
|
11
|
+
[34mESM[39m Build start
|
|
12
|
+
[34mCJS[39m Build start
|
|
13
|
+
[32mESM[39m [1mdist/index.mjs [22m[32m4.55 KB[39m
|
|
14
|
+
[32mESM[39m [1mdist/index.mjs.map [22m[32m10.79 KB[39m
|
|
15
|
+
[32mESM[39m ⚡️ Build success in 74ms
|
|
16
|
+
[32mCJS[39m [1mdist/index.js [22m[32m5.63 KB[39m
|
|
17
|
+
[32mCJS[39m [1mdist/index.js.map [22m[32m10.83 KB[39m
|
|
18
|
+
[32mCJS[39m ⚡️ Build success in 76ms
|
|
19
|
+
[34mDTS[39m Build start
|
|
20
|
+
[32mDTS[39m ⚡️ Build success in 9029ms
|
|
21
|
+
[32mDTS[39m [1mdist/index.d.mts [22m[32m1.69 KB[39m
|
|
22
|
+
[32mDTS[39m [1mdist/index.d.ts [22m[32m1.69 KB[39m
|
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# @objectstack/knowledge-memory
|
|
2
|
+
|
|
3
|
+
## 6.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- f8651cc: Knowledge Protocol MVP — protocol-first RAG via adapter plugins.
|
|
8
|
+
|
|
9
|
+
**What's new:**
|
|
10
|
+
|
|
11
|
+
- `@objectstack/spec` — new `KnowledgeSource` / `KnowledgeDocument` / `KnowledgeChunk` / `KnowledgeHit` schemas (under `@objectstack/spec/ai`) and `IKnowledgeService` / `IKnowledgeAdapter` contracts (under `@objectstack/spec/contracts`).
|
|
12
|
+
- `@objectstack/service-knowledge` — `KnowledgeService` orchestrator + `KnowledgeServicePlugin`. Routes search/index calls to the appropriate adapter, runs **permission-aware retrieval** by re-checking every hit's `sourceRecordId` against the caller's `ExecutionContext` via `IDataEngine` (same RLS that gates plain ObjectQL), and subscribes to `IRealtimeService` for inline record→adapter sync.
|
|
13
|
+
- `@objectstack/knowledge-memory` — deterministic, dependency-free in-memory adapter for dev/tests/reference. Hash-token embedder + brute-force cosine + paragraph chunking.
|
|
14
|
+
- `@objectstack/knowledge-ragflow` — production-grade adapter against the Apache-2.0 [RAGFlow](https://github.com/infiniflow/ragflow) REST API. Plug in your dataset id; ObjectStack handles permission filtering after retrieval.
|
|
15
|
+
- `@objectstack/service-ai` — new `search_knowledge` tool wired through the registry. Threads the LLM caller's actor into `KnowledgeService.search` so retrieval honours RLS automatically.
|
|
16
|
+
|
|
17
|
+
**Why this design:** ObjectStack does NOT own chunking / embedding / vector storage / rerank — those are commodity capabilities best handled by mature OSS (RAGFlow, LlamaIndex, Dify, …). What ObjectStack uniquely owns is the protocol + permission-aware orchestration on top.
|
|
18
|
+
|
|
19
|
+
See `content/docs/protocol/knowledge.mdx` for the full design.
|
|
20
|
+
|
|
21
|
+
### Patch Changes
|
|
22
|
+
|
|
23
|
+
- Updated dependencies [f8651cc]
|
|
24
|
+
- Updated dependencies [f8651cc]
|
|
25
|
+
- Updated dependencies [0bf6f9a]
|
|
26
|
+
- @objectstack/spec@6.4.0
|
|
27
|
+
- @objectstack/service-knowledge@6.4.0
|
|
28
|
+
- @objectstack/core@6.4.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute
|
|
108
|
+
must include a readable copy of the attribution notices
|
|
109
|
+
contained within such NOTICE file, excluding those notices
|
|
110
|
+
that do not pertain to any part of the Derivative Works,
|
|
111
|
+
in at least one of the following places: within a NOTICE
|
|
112
|
+
text file distributed as part of the Derivative Works; within
|
|
113
|
+
the Source form or documentation, if provided along with
|
|
114
|
+
the Derivative Works; or, within a display generated by the
|
|
115
|
+
Derivative Works, if and wherever such third-party notices
|
|
116
|
+
normally appear. The contents of the NOTICE file are for
|
|
117
|
+
informational purposes only and do not modify the License.
|
|
118
|
+
You may add Your own attribution notices within Derivative
|
|
119
|
+
Works that You distribute, alongside or as an addendum to
|
|
120
|
+
the NOTICE text from the Work, provided that such additional
|
|
121
|
+
attribution notices cannot be construed as modifying the
|
|
122
|
+
License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 ObjectStack
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# @objectstack/knowledge-memory
|
|
2
|
+
|
|
3
|
+
In-memory `IKnowledgeAdapter` for ObjectStack — chunks documents, embeds with a deterministic hash-based embedder, and answers `search()` via brute-force cosine similarity.
|
|
4
|
+
|
|
5
|
+
**Purpose**: dev environments, tests, and the reference implementation for the Knowledge Protocol. **Not for production** — there is no persistence, no real semantic understanding, and recall is bounded by simple token overlap.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { ObjectKernel } from '@objectstack/core';
|
|
9
|
+
import { KnowledgeServicePlugin } from '@objectstack/service-knowledge';
|
|
10
|
+
import { KnowledgeMemoryPlugin } from '@objectstack/knowledge-memory';
|
|
11
|
+
|
|
12
|
+
const kernel = new ObjectKernel();
|
|
13
|
+
kernel.use(new KnowledgeServicePlugin({
|
|
14
|
+
sources: [{ id: 'task_notes', label: 'Notes', adapter: 'memory',
|
|
15
|
+
source: { kind: 'object', object: 'task', contentFields: ['notes'] }}],
|
|
16
|
+
}));
|
|
17
|
+
kernel.use(new KnowledgeMemoryPlugin());
|
|
18
|
+
```
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { IKnowledgeAdapter, AdapterContext, AdapterSearchOptions } from '@objectstack/spec/contracts';
|
|
2
|
+
import { KnowledgeDocument, KnowledgeHit } from '@objectstack/spec/ai';
|
|
3
|
+
import { Plugin, PluginContext } from '@objectstack/core';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* In-memory knowledge adapter. Stores per-source document maps,
|
|
7
|
+
* chunks documents naively on paragraph boundaries (with a soft 800-char
|
|
8
|
+
* cap), embeds each chunk as a sparse token-frequency vector, and
|
|
9
|
+
* answers `search()` via brute-force cosine similarity.
|
|
10
|
+
*
|
|
11
|
+
* Deterministic — same input always produces the same hits — so it's
|
|
12
|
+
* great for tests and reference implementations. **Don't use in prod.**
|
|
13
|
+
*/
|
|
14
|
+
declare class KnowledgeMemoryAdapter implements IKnowledgeAdapter {
|
|
15
|
+
readonly id: string;
|
|
16
|
+
private readonly store;
|
|
17
|
+
constructor(id?: string);
|
|
18
|
+
upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise<void>;
|
|
19
|
+
delete(documentIds: string[], ctx: AdapterContext): Promise<void>;
|
|
20
|
+
search(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]>;
|
|
21
|
+
healthCheck(): Promise<{
|
|
22
|
+
ok: boolean;
|
|
23
|
+
message?: string;
|
|
24
|
+
}>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface KnowledgeMemoryPluginOptions {
|
|
28
|
+
/** Adapter id. @default 'memory' */
|
|
29
|
+
id?: string;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* `KnowledgeMemoryPlugin` — registers a `KnowledgeMemoryAdapter` with
|
|
33
|
+
* the host's `IKnowledgeService` during `start()`.
|
|
34
|
+
*/
|
|
35
|
+
declare class KnowledgeMemoryPlugin implements Plugin {
|
|
36
|
+
name: string;
|
|
37
|
+
version: string;
|
|
38
|
+
type: string;
|
|
39
|
+
private readonly adapter;
|
|
40
|
+
constructor(opts?: KnowledgeMemoryPluginOptions);
|
|
41
|
+
init(_ctx: PluginContext): Promise<void>;
|
|
42
|
+
start(ctx: PluginContext): Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export { KnowledgeMemoryAdapter, KnowledgeMemoryPlugin, type KnowledgeMemoryPluginOptions };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { IKnowledgeAdapter, AdapterContext, AdapterSearchOptions } from '@objectstack/spec/contracts';
|
|
2
|
+
import { KnowledgeDocument, KnowledgeHit } from '@objectstack/spec/ai';
|
|
3
|
+
import { Plugin, PluginContext } from '@objectstack/core';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* In-memory knowledge adapter. Stores per-source document maps,
|
|
7
|
+
* chunks documents naively on paragraph boundaries (with a soft 800-char
|
|
8
|
+
* cap), embeds each chunk as a sparse token-frequency vector, and
|
|
9
|
+
* answers `search()` via brute-force cosine similarity.
|
|
10
|
+
*
|
|
11
|
+
* Deterministic — same input always produces the same hits — so it's
|
|
12
|
+
* great for tests and reference implementations. **Don't use in prod.**
|
|
13
|
+
*/
|
|
14
|
+
declare class KnowledgeMemoryAdapter implements IKnowledgeAdapter {
|
|
15
|
+
readonly id: string;
|
|
16
|
+
private readonly store;
|
|
17
|
+
constructor(id?: string);
|
|
18
|
+
upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise<void>;
|
|
19
|
+
delete(documentIds: string[], ctx: AdapterContext): Promise<void>;
|
|
20
|
+
search(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]>;
|
|
21
|
+
healthCheck(): Promise<{
|
|
22
|
+
ok: boolean;
|
|
23
|
+
message?: string;
|
|
24
|
+
}>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface KnowledgeMemoryPluginOptions {
|
|
28
|
+
/** Adapter id. @default 'memory' */
|
|
29
|
+
id?: string;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* `KnowledgeMemoryPlugin` — registers a `KnowledgeMemoryAdapter` with
|
|
33
|
+
* the host's `IKnowledgeService` during `start()`.
|
|
34
|
+
*/
|
|
35
|
+
declare class KnowledgeMemoryPlugin implements Plugin {
|
|
36
|
+
name: string;
|
|
37
|
+
version: string;
|
|
38
|
+
type: string;
|
|
39
|
+
private readonly adapter;
|
|
40
|
+
constructor(opts?: KnowledgeMemoryPluginOptions);
|
|
41
|
+
init(_ctx: PluginContext): Promise<void>;
|
|
42
|
+
start(ctx: PluginContext): Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export { KnowledgeMemoryAdapter, KnowledgeMemoryPlugin, type KnowledgeMemoryPluginOptions };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
KnowledgeMemoryAdapter: () => KnowledgeMemoryAdapter,
|
|
24
|
+
KnowledgeMemoryPlugin: () => KnowledgeMemoryPlugin
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(index_exports);
|
|
27
|
+
var import_contracts = require("@objectstack/spec/contracts");
|
|
28
|
+
var KnowledgeMemoryAdapter = class {
|
|
29
|
+
constructor(id = "memory") {
|
|
30
|
+
this.store = /* @__PURE__ */ new Map();
|
|
31
|
+
this.id = id;
|
|
32
|
+
}
|
|
33
|
+
async upsert(docs, ctx) {
|
|
34
|
+
const sourceId = ctx.source.id;
|
|
35
|
+
const existing = this.store.get(sourceId) ?? [];
|
|
36
|
+
const byDoc = /* @__PURE__ */ new Map();
|
|
37
|
+
for (const c of existing) {
|
|
38
|
+
const arr = byDoc.get(c.documentId) ?? [];
|
|
39
|
+
arr.push(c);
|
|
40
|
+
byDoc.set(c.documentId, arr);
|
|
41
|
+
}
|
|
42
|
+
for (const doc of docs) {
|
|
43
|
+
byDoc.set(doc.id, chunkAndEmbed(doc));
|
|
44
|
+
}
|
|
45
|
+
this.store.set(sourceId, Array.from(byDoc.values()).flat());
|
|
46
|
+
}
|
|
47
|
+
async delete(documentIds, ctx) {
|
|
48
|
+
const sourceId = ctx.source.id;
|
|
49
|
+
const chunks = this.store.get(sourceId);
|
|
50
|
+
if (!chunks) return;
|
|
51
|
+
const dropSet = new Set(documentIds);
|
|
52
|
+
this.store.set(
|
|
53
|
+
sourceId,
|
|
54
|
+
chunks.filter((c) => !dropSet.has(c.documentId))
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
async search(query, opts) {
|
|
58
|
+
const chunks = this.store.get(opts.source.id) ?? [];
|
|
59
|
+
if (chunks.length === 0) return [];
|
|
60
|
+
const qVec = embedTokens(tokenize(query));
|
|
61
|
+
const qNorm = vectorNorm(qVec);
|
|
62
|
+
if (qNorm === 0) return [];
|
|
63
|
+
const filter = opts.filter ?? {};
|
|
64
|
+
const filtered = Object.keys(filter).length ? chunks.filter((c) => matchesFilter(c.metadata, filter)) : chunks;
|
|
65
|
+
const scored = filtered.map((c) => ({
|
|
66
|
+
chunk: c,
|
|
67
|
+
score: cosineSimilarity(qVec, c.vector, qNorm, c.vectorNorm)
|
|
68
|
+
}));
|
|
69
|
+
scored.sort((a, b) => b.score - a.score);
|
|
70
|
+
const top = scored.slice(0, opts.topK).filter((s) => s.score > 0);
|
|
71
|
+
return top.map(({ chunk, score }) => ({
|
|
72
|
+
chunkId: chunk.chunkId,
|
|
73
|
+
documentId: chunk.documentId,
|
|
74
|
+
sourceId: opts.source.id,
|
|
75
|
+
sourceRecordId: chunk.sourceRecordId,
|
|
76
|
+
score,
|
|
77
|
+
snippet: chunk.content,
|
|
78
|
+
title: chunk.title,
|
|
79
|
+
metadata: chunk.metadata
|
|
80
|
+
}));
|
|
81
|
+
}
|
|
82
|
+
async healthCheck() {
|
|
83
|
+
return { ok: true, message: `memory adapter (${this.store.size} sources)` };
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
var CHUNK_TARGET = 800;
|
|
87
|
+
function chunkAndEmbed(doc) {
|
|
88
|
+
const paragraphs = doc.content.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean);
|
|
89
|
+
const chunks = [];
|
|
90
|
+
let buf = "";
|
|
91
|
+
for (const p of paragraphs.length ? paragraphs : [doc.content]) {
|
|
92
|
+
if (buf && buf.length + p.length + 2 > CHUNK_TARGET) {
|
|
93
|
+
chunks.push(buf);
|
|
94
|
+
buf = "";
|
|
95
|
+
}
|
|
96
|
+
if (p.length > CHUNK_TARGET) {
|
|
97
|
+
if (buf) {
|
|
98
|
+
chunks.push(buf);
|
|
99
|
+
buf = "";
|
|
100
|
+
}
|
|
101
|
+
for (let i = 0; i < p.length; i += CHUNK_TARGET) {
|
|
102
|
+
chunks.push(p.slice(i, i + CHUNK_TARGET));
|
|
103
|
+
}
|
|
104
|
+
} else {
|
|
105
|
+
buf = buf ? `${buf}
|
|
106
|
+
|
|
107
|
+
${p}` : p;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (buf) chunks.push(buf);
|
|
111
|
+
return chunks.map((content, idx) => {
|
|
112
|
+
const vec = embedTokens(tokenize(content));
|
|
113
|
+
return {
|
|
114
|
+
chunkId: `${doc.id}#${idx}`,
|
|
115
|
+
documentId: doc.id,
|
|
116
|
+
sourceRecordId: doc.sourceRecordId,
|
|
117
|
+
content,
|
|
118
|
+
title: doc.title,
|
|
119
|
+
metadata: doc.metadata ?? {},
|
|
120
|
+
vector: vec,
|
|
121
|
+
vectorNorm: vectorNorm(vec)
|
|
122
|
+
};
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
function tokenize(text) {
|
|
126
|
+
return text.toLowerCase().split(/[^a-z0-9\u4e00-\u9fff]+/i).filter((t) => t.length > 1);
|
|
127
|
+
}
|
|
128
|
+
function embedTokens(tokens) {
|
|
129
|
+
const vec = /* @__PURE__ */ new Map();
|
|
130
|
+
for (const t of tokens) vec.set(t, (vec.get(t) ?? 0) + 1);
|
|
131
|
+
return vec;
|
|
132
|
+
}
|
|
133
|
+
function vectorNorm(v) {
|
|
134
|
+
let s = 0;
|
|
135
|
+
for (const x of v.values()) s += x * x;
|
|
136
|
+
return Math.sqrt(s);
|
|
137
|
+
}
|
|
138
|
+
function cosineSimilarity(a, b, aNorm = vectorNorm(a), bNorm = vectorNorm(b)) {
|
|
139
|
+
if (aNorm === 0 || bNorm === 0) return 0;
|
|
140
|
+
const [small, big] = a.size < b.size ? [a, b] : [b, a];
|
|
141
|
+
let dot = 0;
|
|
142
|
+
for (const [k, v] of small) {
|
|
143
|
+
const w = big.get(k);
|
|
144
|
+
if (w) dot += v * w;
|
|
145
|
+
}
|
|
146
|
+
return dot / (aNorm * bNorm);
|
|
147
|
+
}
|
|
148
|
+
function matchesFilter(metadata, filter) {
|
|
149
|
+
for (const [k, v] of Object.entries(filter)) {
|
|
150
|
+
if (metadata[k] !== v) return false;
|
|
151
|
+
}
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
var KnowledgeMemoryPlugin = class {
|
|
155
|
+
constructor(opts = {}) {
|
|
156
|
+
this.name = "com.objectstack.plugin.knowledge-memory";
|
|
157
|
+
this.version = "0.1.0";
|
|
158
|
+
this.type = "standard";
|
|
159
|
+
this.adapter = new KnowledgeMemoryAdapter(opts.id ?? "memory");
|
|
160
|
+
}
|
|
161
|
+
async init(_ctx) {
|
|
162
|
+
}
|
|
163
|
+
async start(ctx) {
|
|
164
|
+
let svc;
|
|
165
|
+
try {
|
|
166
|
+
svc = ctx.getService(import_contracts.KNOWLEDGE_SERVICE);
|
|
167
|
+
} catch {
|
|
168
|
+
ctx.logger.warn?.(
|
|
169
|
+
"KnowledgeMemoryPlugin: IKnowledgeService not registered \u2014 install KnowledgeServicePlugin first."
|
|
170
|
+
);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
svc.registerAdapter(this.adapter.id, this.adapter);
|
|
174
|
+
ctx.logger.info?.(`KnowledgeMemoryPlugin: adapter '${this.adapter.id}' registered.`);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
178
|
+
0 && (module.exports = {
|
|
179
|
+
KnowledgeMemoryAdapter,
|
|
180
|
+
KnowledgeMemoryPlugin
|
|
181
|
+
});
|
|
182
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n IKnowledgeAdapter,\n IKnowledgeService,\n AdapterContext,\n AdapterSearchOptions,\n} from '@objectstack/spec/contracts';\nimport type {\n KnowledgeDocument,\n KnowledgeHit,\n} from '@objectstack/spec/ai';\nimport { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';\n\n/**\n * In-memory knowledge adapter. Stores per-source document maps,\n * chunks documents naively on paragraph boundaries (with a soft 800-char\n * cap), embeds each chunk as a sparse token-frequency vector, and\n * answers `search()` via brute-force cosine similarity.\n *\n * Deterministic — same input always produces the same hits — so it's\n * great for tests and reference implementations. **Don't use in prod.**\n */\nexport class KnowledgeMemoryAdapter implements IKnowledgeAdapter {\n readonly id: string;\n private readonly store = new Map<string, ChunkRecord[]>();\n\n constructor(id = 'memory') {\n this.id = id;\n }\n\n async upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise<void> {\n const sourceId = ctx.source.id;\n const existing = this.store.get(sourceId) ?? [];\n const byDoc = new Map<string, ChunkRecord[]>();\n for (const c of existing) {\n const arr = byDoc.get(c.documentId) ?? [];\n arr.push(c);\n byDoc.set(c.documentId, arr);\n }\n for (const doc of docs) {\n byDoc.set(doc.id, chunkAndEmbed(doc));\n }\n this.store.set(sourceId, Array.from(byDoc.values()).flat());\n }\n\n async delete(documentIds: string[], ctx: AdapterContext): Promise<void> {\n const sourceId = ctx.source.id;\n const chunks = this.store.get(sourceId);\n if (!chunks) return;\n const dropSet = new Set(documentIds);\n this.store.set(\n sourceId,\n chunks.filter((c) => !dropSet.has(c.documentId)),\n );\n }\n\n async search(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]> {\n const chunks = this.store.get(opts.source.id) ?? [];\n if (chunks.length === 0) return [];\n const qVec = embedTokens(tokenize(query));\n const qNorm = vectorNorm(qVec);\n if (qNorm === 0) return [];\n\n const filter = opts.filter ?? {};\n const filtered = Object.keys(filter).length\n ? chunks.filter((c) => matchesFilter(c.metadata, filter))\n : chunks;\n\n const scored = filtered.map((c) => ({\n chunk: c,\n score: cosineSimilarity(qVec, c.vector, qNorm, c.vectorNorm),\n }));\n scored.sort((a, b) => b.score - a.score);\n const top = scored.slice(0, opts.topK).filter((s) => s.score > 0);\n return top.map<KnowledgeHit>(({ chunk, score }) => ({\n chunkId: chunk.chunkId,\n documentId: chunk.documentId,\n sourceId: opts.source.id,\n sourceRecordId: chunk.sourceRecordId,\n score,\n snippet: chunk.content,\n title: chunk.title,\n metadata: chunk.metadata,\n }));\n }\n\n async healthCheck(): Promise<{ ok: boolean; message?: string }> {\n return { ok: true, message: `memory adapter (${this.store.size} sources)` };\n }\n}\n\ninterface ChunkRecord {\n chunkId: string;\n documentId: string;\n sourceRecordId?: string;\n content: string;\n title?: string;\n metadata: Record<string, unknown>;\n vector: Map<string, number>;\n vectorNorm: number;\n}\n\nconst CHUNK_TARGET = 800;\n\nfunction chunkAndEmbed(doc: KnowledgeDocument): ChunkRecord[] {\n const paragraphs = doc.content\n .split(/\\n{2,}/)\n .map((p) => p.trim())\n .filter(Boolean);\n const chunks: string[] = [];\n let buf = '';\n for (const p of paragraphs.length ? paragraphs : [doc.content]) {\n if (buf && buf.length + p.length + 2 > CHUNK_TARGET) {\n chunks.push(buf);\n buf = '';\n }\n if (p.length > CHUNK_TARGET) {\n if (buf) {\n chunks.push(buf);\n buf = '';\n }\n for (let i = 0; i < p.length; i += CHUNK_TARGET) {\n chunks.push(p.slice(i, i + CHUNK_TARGET));\n }\n } else {\n buf = buf ? `${buf}\\n\\n${p}` : p;\n }\n }\n if (buf) chunks.push(buf);\n return chunks.map((content, idx) => {\n const vec = embedTokens(tokenize(content));\n return {\n chunkId: `${doc.id}#${idx}`,\n documentId: doc.id,\n sourceRecordId: doc.sourceRecordId,\n content,\n title: doc.title,\n metadata: doc.metadata ?? {},\n vector: vec,\n vectorNorm: vectorNorm(vec),\n };\n });\n}\n\nfunction tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .split(/[^a-z0-9\\u4e00-\\u9fff]+/i)\n .filter((t) => t.length > 1);\n}\n\nfunction embedTokens(tokens: string[]): Map<string, number> {\n const vec = new Map<string, number>();\n for (const t of tokens) vec.set(t, (vec.get(t) ?? 0) + 1);\n return vec;\n}\n\nfunction vectorNorm(v: Map<string, number>): number {\n let s = 0;\n for (const x of v.values()) s += x * x;\n return Math.sqrt(s);\n}\n\nfunction cosineSimilarity(\n a: Map<string, number>,\n b: Map<string, number>,\n aNorm = vectorNorm(a),\n bNorm = vectorNorm(b),\n): number {\n if (aNorm === 0 || bNorm === 0) return 0;\n // iterate smaller map\n const [small, big] = a.size < b.size ? [a, b] : [b, a];\n let dot = 0;\n for (const [k, v] of small) {\n const w = big.get(k);\n if (w) dot += v * w;\n }\n return dot / (aNorm * bNorm);\n}\n\nfunction matchesFilter(\n metadata: Record<string, unknown>,\n filter: Record<string, unknown>,\n): boolean {\n for (const [k, v] of Object.entries(filter)) {\n if (metadata[k] !== v) return false;\n }\n return true;\n}\n\n/* ---------------------------------------------------------------- */\n/* Kernel plugin glue */\n/* ---------------------------------------------------------------- */\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\n\nexport interface KnowledgeMemoryPluginOptions {\n /** Adapter id. @default 'memory' */\n id?: string;\n}\n\n/**\n * `KnowledgeMemoryPlugin` — registers a `KnowledgeMemoryAdapter` with\n * the host's `IKnowledgeService` during `start()`.\n */\nexport class KnowledgeMemoryPlugin implements Plugin {\n name = 'com.objectstack.plugin.knowledge-memory';\n version = '0.1.0';\n type = 'standard';\n\n private readonly adapter: KnowledgeMemoryAdapter;\n\n constructor(opts: KnowledgeMemoryPluginOptions = {}) {\n this.adapter = new KnowledgeMemoryAdapter(opts.id ?? 'memory');\n }\n\n async init(_ctx: PluginContext): Promise<void> {\n // No-op: registration happens in start() once IKnowledgeService is up.\n }\n\n async start(ctx: PluginContext): Promise<void> {\n let svc: IKnowledgeService | undefined;\n try {\n svc = ctx.getService<IKnowledgeService>(KNOWLEDGE_SERVICE);\n } catch {\n ctx.logger.warn?.(\n 'KnowledgeMemoryPlugin: IKnowledgeService not registered — install KnowledgeServicePlugin first.',\n );\n return;\n }\n svc.registerAdapter(this.adapter.id, this.adapter);\n ctx.logger.info?.(`KnowledgeMemoryPlugin: adapter '${this.adapter.id}' registered.`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;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CAAC,GAAG,CAAC;AACrD,MAAI,MAAM;AACV,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO;AAC1B,UAAM,IAAI,IAAI,IAAI,CAAC;AACnB,QAAI,EAAG,QAAO,IAAI;AAAA,EACpB;AACA,SAAO,OAAO,QAAQ;AACxB;AAEA,SAAS,cACP,UACA,QACS;AACT,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,MAAM,GAAG;AAC3C,QAAI,SAAS,CAAC,MAAM,EAAG,QAAO;AAAA,EAChC;AACA,SAAO;AACT;AAiBO,IAAM,wBAAN,MAA8C;AAAA,EAOnD,YAAY,OAAqC,CAAC,GAAG;AANrD,gBAAO;AACP,mBAAU;AACV,gBAAO;AAKL,SAAK,UAAU,IAAI,uBAAuB,KAAK,MAAM,QAAQ;AAAA,EAC/D;AAAA,EAEA,MAAM,KAAK,MAAoC;AAAA,EAE/C;AAAA,EAEA,MAAM,MAAM,KAAmC;AAC7C,QAAI;AACJ,QAAI;AACF,YAAM,IAAI,WAA8B,kCAAiB;AAAA,IAC3D,QAAQ;AACN,UAAI,OAAO;AAAA,QACT;AAAA,MACF;AACA;AAAA,IACF;AACA,QAAI,gBAAgB,KAAK,QAAQ,IAAI,KAAK,OAAO;AACjD,QAAI,OAAO,OAAO,mCAAmC,KAAK,QAAQ,EAAE,eAAe;AAAA,EACrF;AACF;","names":[]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { KNOWLEDGE_SERVICE } from "@objectstack/spec/contracts";
|
|
3
|
+
var KnowledgeMemoryAdapter = class {
|
|
4
|
+
constructor(id = "memory") {
|
|
5
|
+
this.store = /* @__PURE__ */ new Map();
|
|
6
|
+
this.id = id;
|
|
7
|
+
}
|
|
8
|
+
async upsert(docs, ctx) {
|
|
9
|
+
const sourceId = ctx.source.id;
|
|
10
|
+
const existing = this.store.get(sourceId) ?? [];
|
|
11
|
+
const byDoc = /* @__PURE__ */ new Map();
|
|
12
|
+
for (const c of existing) {
|
|
13
|
+
const arr = byDoc.get(c.documentId) ?? [];
|
|
14
|
+
arr.push(c);
|
|
15
|
+
byDoc.set(c.documentId, arr);
|
|
16
|
+
}
|
|
17
|
+
for (const doc of docs) {
|
|
18
|
+
byDoc.set(doc.id, chunkAndEmbed(doc));
|
|
19
|
+
}
|
|
20
|
+
this.store.set(sourceId, Array.from(byDoc.values()).flat());
|
|
21
|
+
}
|
|
22
|
+
async delete(documentIds, ctx) {
|
|
23
|
+
const sourceId = ctx.source.id;
|
|
24
|
+
const chunks = this.store.get(sourceId);
|
|
25
|
+
if (!chunks) return;
|
|
26
|
+
const dropSet = new Set(documentIds);
|
|
27
|
+
this.store.set(
|
|
28
|
+
sourceId,
|
|
29
|
+
chunks.filter((c) => !dropSet.has(c.documentId))
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
async search(query, opts) {
|
|
33
|
+
const chunks = this.store.get(opts.source.id) ?? [];
|
|
34
|
+
if (chunks.length === 0) return [];
|
|
35
|
+
const qVec = embedTokens(tokenize(query));
|
|
36
|
+
const qNorm = vectorNorm(qVec);
|
|
37
|
+
if (qNorm === 0) return [];
|
|
38
|
+
const filter = opts.filter ?? {};
|
|
39
|
+
const filtered = Object.keys(filter).length ? chunks.filter((c) => matchesFilter(c.metadata, filter)) : chunks;
|
|
40
|
+
const scored = filtered.map((c) => ({
|
|
41
|
+
chunk: c,
|
|
42
|
+
score: cosineSimilarity(qVec, c.vector, qNorm, c.vectorNorm)
|
|
43
|
+
}));
|
|
44
|
+
scored.sort((a, b) => b.score - a.score);
|
|
45
|
+
const top = scored.slice(0, opts.topK).filter((s) => s.score > 0);
|
|
46
|
+
return top.map(({ chunk, score }) => ({
|
|
47
|
+
chunkId: chunk.chunkId,
|
|
48
|
+
documentId: chunk.documentId,
|
|
49
|
+
sourceId: opts.source.id,
|
|
50
|
+
sourceRecordId: chunk.sourceRecordId,
|
|
51
|
+
score,
|
|
52
|
+
snippet: chunk.content,
|
|
53
|
+
title: chunk.title,
|
|
54
|
+
metadata: chunk.metadata
|
|
55
|
+
}));
|
|
56
|
+
}
|
|
57
|
+
async healthCheck() {
|
|
58
|
+
return { ok: true, message: `memory adapter (${this.store.size} sources)` };
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
var CHUNK_TARGET = 800;
|
|
62
|
+
function chunkAndEmbed(doc) {
|
|
63
|
+
const paragraphs = doc.content.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean);
|
|
64
|
+
const chunks = [];
|
|
65
|
+
let buf = "";
|
|
66
|
+
for (const p of paragraphs.length ? paragraphs : [doc.content]) {
|
|
67
|
+
if (buf && buf.length + p.length + 2 > CHUNK_TARGET) {
|
|
68
|
+
chunks.push(buf);
|
|
69
|
+
buf = "";
|
|
70
|
+
}
|
|
71
|
+
if (p.length > CHUNK_TARGET) {
|
|
72
|
+
if (buf) {
|
|
73
|
+
chunks.push(buf);
|
|
74
|
+
buf = "";
|
|
75
|
+
}
|
|
76
|
+
for (let i = 0; i < p.length; i += CHUNK_TARGET) {
|
|
77
|
+
chunks.push(p.slice(i, i + CHUNK_TARGET));
|
|
78
|
+
}
|
|
79
|
+
} else {
|
|
80
|
+
buf = buf ? `${buf}
|
|
81
|
+
|
|
82
|
+
${p}` : p;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (buf) chunks.push(buf);
|
|
86
|
+
return chunks.map((content, idx) => {
|
|
87
|
+
const vec = embedTokens(tokenize(content));
|
|
88
|
+
return {
|
|
89
|
+
chunkId: `${doc.id}#${idx}`,
|
|
90
|
+
documentId: doc.id,
|
|
91
|
+
sourceRecordId: doc.sourceRecordId,
|
|
92
|
+
content,
|
|
93
|
+
title: doc.title,
|
|
94
|
+
metadata: doc.metadata ?? {},
|
|
95
|
+
vector: vec,
|
|
96
|
+
vectorNorm: vectorNorm(vec)
|
|
97
|
+
};
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
function tokenize(text) {
|
|
101
|
+
return text.toLowerCase().split(/[^a-z0-9\u4e00-\u9fff]+/i).filter((t) => t.length > 1);
|
|
102
|
+
}
|
|
103
|
+
function embedTokens(tokens) {
|
|
104
|
+
const vec = /* @__PURE__ */ new Map();
|
|
105
|
+
for (const t of tokens) vec.set(t, (vec.get(t) ?? 0) + 1);
|
|
106
|
+
return vec;
|
|
107
|
+
}
|
|
108
|
+
function vectorNorm(v) {
|
|
109
|
+
let s = 0;
|
|
110
|
+
for (const x of v.values()) s += x * x;
|
|
111
|
+
return Math.sqrt(s);
|
|
112
|
+
}
|
|
113
|
+
function cosineSimilarity(a, b, aNorm = vectorNorm(a), bNorm = vectorNorm(b)) {
|
|
114
|
+
if (aNorm === 0 || bNorm === 0) return 0;
|
|
115
|
+
const [small, big] = a.size < b.size ? [a, b] : [b, a];
|
|
116
|
+
let dot = 0;
|
|
117
|
+
for (const [k, v] of small) {
|
|
118
|
+
const w = big.get(k);
|
|
119
|
+
if (w) dot += v * w;
|
|
120
|
+
}
|
|
121
|
+
return dot / (aNorm * bNorm);
|
|
122
|
+
}
|
|
123
|
+
function matchesFilter(metadata, filter) {
|
|
124
|
+
for (const [k, v] of Object.entries(filter)) {
|
|
125
|
+
if (metadata[k] !== v) return false;
|
|
126
|
+
}
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
var KnowledgeMemoryPlugin = class {
|
|
130
|
+
constructor(opts = {}) {
|
|
131
|
+
this.name = "com.objectstack.plugin.knowledge-memory";
|
|
132
|
+
this.version = "0.1.0";
|
|
133
|
+
this.type = "standard";
|
|
134
|
+
this.adapter = new KnowledgeMemoryAdapter(opts.id ?? "memory");
|
|
135
|
+
}
|
|
136
|
+
async init(_ctx) {
|
|
137
|
+
}
|
|
138
|
+
async start(ctx) {
|
|
139
|
+
let svc;
|
|
140
|
+
try {
|
|
141
|
+
svc = ctx.getService(KNOWLEDGE_SERVICE);
|
|
142
|
+
} catch {
|
|
143
|
+
ctx.logger.warn?.(
|
|
144
|
+
"KnowledgeMemoryPlugin: IKnowledgeService not registered \u2014 install KnowledgeServicePlugin first."
|
|
145
|
+
);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
svc.registerAdapter(this.adapter.id, this.adapter);
|
|
149
|
+
ctx.logger.info?.(`KnowledgeMemoryPlugin: adapter '${this.adapter.id}' registered.`);
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
export {
|
|
153
|
+
KnowledgeMemoryAdapter,
|
|
154
|
+
KnowledgeMemoryPlugin
|
|
155
|
+
};
|
|
156
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type {\n IKnowledgeAdapter,\n IKnowledgeService,\n AdapterContext,\n AdapterSearchOptions,\n} from '@objectstack/spec/contracts';\nimport type {\n KnowledgeDocument,\n KnowledgeHit,\n} from '@objectstack/spec/ai';\nimport { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';\n\n/**\n * In-memory knowledge adapter. Stores per-source document maps,\n * chunks documents naively on paragraph boundaries (with a soft 800-char\n * cap), embeds each chunk as a sparse token-frequency vector, and\n * answers `search()` via brute-force cosine similarity.\n *\n * Deterministic — same input always produces the same hits — so it's\n * great for tests and reference implementations. **Don't use in prod.**\n */\nexport class KnowledgeMemoryAdapter implements IKnowledgeAdapter {\n readonly id: string;\n private readonly store = new Map<string, ChunkRecord[]>();\n\n constructor(id = 'memory') {\n this.id = id;\n }\n\n async upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise<void> {\n const sourceId = ctx.source.id;\n const existing = this.store.get(sourceId) ?? [];\n const byDoc = new Map<string, ChunkRecord[]>();\n for (const c of existing) {\n const arr = byDoc.get(c.documentId) ?? [];\n arr.push(c);\n byDoc.set(c.documentId, arr);\n }\n for (const doc of docs) {\n byDoc.set(doc.id, chunkAndEmbed(doc));\n }\n this.store.set(sourceId, Array.from(byDoc.values()).flat());\n }\n\n async delete(documentIds: string[], ctx: AdapterContext): Promise<void> {\n const sourceId = ctx.source.id;\n const chunks = this.store.get(sourceId);\n if (!chunks) return;\n const dropSet = new Set(documentIds);\n this.store.set(\n sourceId,\n chunks.filter((c) => !dropSet.has(c.documentId)),\n );\n }\n\n async search(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]> {\n const chunks = this.store.get(opts.source.id) ?? [];\n if (chunks.length === 0) return [];\n const qVec = embedTokens(tokenize(query));\n const qNorm = vectorNorm(qVec);\n if (qNorm === 0) return [];\n\n const filter = opts.filter ?? {};\n const filtered = Object.keys(filter).length\n ? chunks.filter((c) => matchesFilter(c.metadata, filter))\n : chunks;\n\n const scored = filtered.map((c) => ({\n chunk: c,\n score: cosineSimilarity(qVec, c.vector, qNorm, c.vectorNorm),\n }));\n scored.sort((a, b) => b.score - a.score);\n const top = scored.slice(0, opts.topK).filter((s) => s.score > 0);\n return top.map<KnowledgeHit>(({ chunk, score }) => ({\n chunkId: chunk.chunkId,\n documentId: chunk.documentId,\n sourceId: opts.source.id,\n sourceRecordId: chunk.sourceRecordId,\n score,\n snippet: chunk.content,\n title: chunk.title,\n metadata: chunk.metadata,\n }));\n }\n\n async healthCheck(): Promise<{ ok: boolean; message?: string }> {\n return { ok: true, message: `memory adapter (${this.store.size} sources)` };\n }\n}\n\ninterface ChunkRecord {\n chunkId: string;\n documentId: string;\n sourceRecordId?: string;\n content: string;\n title?: string;\n metadata: Record<string, unknown>;\n vector: Map<string, number>;\n vectorNorm: number;\n}\n\nconst CHUNK_TARGET = 800;\n\nfunction chunkAndEmbed(doc: KnowledgeDocument): ChunkRecord[] {\n const paragraphs = doc.content\n .split(/\\n{2,}/)\n .map((p) => p.trim())\n .filter(Boolean);\n const chunks: string[] = [];\n let buf = '';\n for (const p of paragraphs.length ? paragraphs : [doc.content]) {\n if (buf && buf.length + p.length + 2 > CHUNK_TARGET) {\n chunks.push(buf);\n buf = '';\n }\n if (p.length > CHUNK_TARGET) {\n if (buf) {\n chunks.push(buf);\n buf = '';\n }\n for (let i = 0; i < p.length; i += CHUNK_TARGET) {\n chunks.push(p.slice(i, i + CHUNK_TARGET));\n }\n } else {\n buf = buf ? `${buf}\\n\\n${p}` : p;\n }\n }\n if (buf) chunks.push(buf);\n return chunks.map((content, idx) => {\n const vec = embedTokens(tokenize(content));\n return {\n chunkId: `${doc.id}#${idx}`,\n documentId: doc.id,\n sourceRecordId: doc.sourceRecordId,\n content,\n title: doc.title,\n metadata: doc.metadata ?? {},\n vector: vec,\n vectorNorm: vectorNorm(vec),\n };\n });\n}\n\nfunction tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .split(/[^a-z0-9\\u4e00-\\u9fff]+/i)\n .filter((t) => t.length > 1);\n}\n\nfunction embedTokens(tokens: string[]): Map<string, number> {\n const vec = new Map<string, number>();\n for (const t of tokens) vec.set(t, (vec.get(t) ?? 0) + 1);\n return vec;\n}\n\nfunction vectorNorm(v: Map<string, number>): number {\n let s = 0;\n for (const x of v.values()) s += x * x;\n return Math.sqrt(s);\n}\n\nfunction cosineSimilarity(\n a: Map<string, number>,\n b: Map<string, number>,\n aNorm = vectorNorm(a),\n bNorm = vectorNorm(b),\n): number {\n if (aNorm === 0 || bNorm === 0) return 0;\n // iterate smaller map\n const [small, big] = a.size < b.size ? [a, b] : [b, a];\n let dot = 0;\n for (const [k, v] of small) {\n const w = big.get(k);\n if (w) dot += v * w;\n }\n return dot / (aNorm * bNorm);\n}\n\nfunction matchesFilter(\n metadata: Record<string, unknown>,\n filter: Record<string, unknown>,\n): boolean {\n for (const [k, v] of Object.entries(filter)) {\n if (metadata[k] !== v) return false;\n }\n return true;\n}\n\n/* ---------------------------------------------------------------- */\n/* Kernel plugin glue */\n/* ---------------------------------------------------------------- */\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\n\nexport interface KnowledgeMemoryPluginOptions {\n /** Adapter id. @default 'memory' */\n id?: string;\n}\n\n/**\n * `KnowledgeMemoryPlugin` — registers a `KnowledgeMemoryAdapter` with\n * the host's `IKnowledgeService` during `start()`.\n */\nexport class KnowledgeMemoryPlugin implements Plugin {\n name = 'com.objectstack.plugin.knowledge-memory';\n version = '0.1.0';\n type = 'standard';\n\n private readonly adapter: KnowledgeMemoryAdapter;\n\n constructor(opts: KnowledgeMemoryPluginOptions = {}) {\n this.adapter = new KnowledgeMemoryAdapter(opts.id ?? 'memory');\n }\n\n async init(_ctx: PluginContext): Promise<void> {\n // No-op: registration happens in start() once IKnowledgeService is up.\n }\n\n async start(ctx: PluginContext): Promise<void> {\n let svc: IKnowledgeService | undefined;\n try {\n svc = ctx.getService<IKnowledgeService>(KNOWLEDGE_SERVICE);\n } catch {\n ctx.logger.warn?.(\n 'KnowledgeMemoryPlugin: IKnowledgeService not registered — install KnowledgeServicePlugin first.',\n );\n return;\n }\n svc.registerAdapter(this.adapter.id, this.adapter);\n ctx.logger.info?.(`KnowledgeMemoryPlugin: adapter '${this.adapter.id}' registered.`);\n }\n}\n"],"mappings":";AAYA,SAAS,yBAAyB;AAW3B,IAAM,yBAAN,MAA0D;AAAA,EAI/D,YAAY,KAAK,UAAU;AAF3B,SAAiB,QAAQ,oBAAI,IAA2B;AAGtD,SAAK,KAAK;AAAA,EACZ;AAAA,EAEA,MAAM,OAAO,MAA2B,KAAoC;AAC1E,UAAM,WAAW,IAAI,OAAO;AAC5B,UAAM,WAAW,KAAK,MAAM,IAAI,QAAQ,KAAK,CAAC;AAC9C,UAAM,QAAQ,oBAAI,IAA2B;AAC7C,eAAW,KAAK,UAAU;AACxB,YAAM,MAAM,MAAM,IAAI,EAAE,UAAU,KAAK,CAAC;AACxC,UAAI,KAAK,CAAC;AACV,YAAM,IAAI,EAAE,YAAY,GAAG;AAAA,IAC7B;AACA,eAAW,OAAO,MAAM;AACtB,YAAM,IAAI,IAAI,IAAI,cAAc,GAAG,CAAC;AAAA,IACtC;AACA,SAAK,MAAM,IAAI,UAAU,MAAM,KAAK,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AACF,YAAM,IAAI,WAA8B,iBAAiB;AAAA,IAC3D,QAAQ;AACN,UAAI,OAAO;AAAA,QACT;AAAA,MACF;AACA;AAAA,IACF;AACA,QAAI,gBAAgB,KAAK,QAAQ,IAAI,KAAK,OAAO;AACjD,QAAI,OAAO,OAAO,mCAAmC,KAAK,QAAQ,EAAE,eAAe;AAAA,EACrF;AACF;","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@objectstack/knowledge-memory",
|
|
3
|
+
"version": "6.4.0",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"description": "In-memory knowledge adapter for ObjectStack (dev / test reference implementation).",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.mjs",
|
|
12
|
+
"require": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"@objectstack/core": "6.4.0",
|
|
17
|
+
"@objectstack/service-knowledge": "6.4.0",
|
|
18
|
+
"@objectstack/spec": "6.4.0"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"@types/node": "^25.9.1",
|
|
22
|
+
"typescript": "^6.0.3",
|
|
23
|
+
"vitest": "^4.1.7"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"objectstack",
|
|
27
|
+
"knowledge",
|
|
28
|
+
"rag",
|
|
29
|
+
"memory",
|
|
30
|
+
"in-memory"
|
|
31
|
+
],
|
|
32
|
+
"scripts": {
|
|
33
|
+
"build": "tsup --config ../../../tsup.config.ts",
|
|
34
|
+
"dev": "tsc -w",
|
|
35
|
+
"test": "vitest run"
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import { describe, it, expect } from 'vitest';
|
|
4
|
+
import { KnowledgeMemoryAdapter } from '../index';
|
|
5
|
+
import type { KnowledgeDocument } from '@objectstack/spec/ai';
|
|
6
|
+
import type { KnowledgeSource } from '@objectstack/spec/ai';
|
|
7
|
+
|
|
8
|
+
const source: KnowledgeSource = {
|
|
9
|
+
id: 'src1',
|
|
10
|
+
label: 'Test source',
|
|
11
|
+
adapter: 'memory',
|
|
12
|
+
source: { kind: 'http', urls: ['https://example.com'] } as KnowledgeSource['source'],
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const docs: KnowledgeDocument[] = [
|
|
16
|
+
{
|
|
17
|
+
id: 'd1',
|
|
18
|
+
sourceId: 'src1',
|
|
19
|
+
content: 'The quick brown fox jumps over the lazy dog. Foxes are clever animals.',
|
|
20
|
+
title: 'Fox facts',
|
|
21
|
+
metadata: { topic: 'animals' },
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
id: 'd2',
|
|
25
|
+
sourceId: 'src1',
|
|
26
|
+
content: 'Refunds require a receipt and must be processed within 30 days of purchase.',
|
|
27
|
+
title: 'Refund policy',
|
|
28
|
+
metadata: { topic: 'policy' },
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
id: 'd3',
|
|
32
|
+
sourceId: 'src1',
|
|
33
|
+
content: 'Customer support is available 24/7 by email at help@example.com.',
|
|
34
|
+
title: 'Support',
|
|
35
|
+
metadata: { topic: 'policy' },
|
|
36
|
+
},
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
describe('KnowledgeMemoryAdapter', () => {
|
|
40
|
+
it('upsert + search returns the semantically closest doc on top', async () => {
|
|
41
|
+
const a = new KnowledgeMemoryAdapter();
|
|
42
|
+
await a.upsert(docs, { source });
|
|
43
|
+
const hits = await a.search('how do refunds work', { source, topK: 3 });
|
|
44
|
+
expect(hits.length).toBeGreaterThan(0);
|
|
45
|
+
expect(hits[0].documentId).toBe('d2');
|
|
46
|
+
expect(hits[0].score).toBeGreaterThan(0);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('respects topK', async () => {
|
|
50
|
+
const a = new KnowledgeMemoryAdapter();
|
|
51
|
+
await a.upsert(docs, { source });
|
|
52
|
+
const hits = await a.search('refund support fox', { source, topK: 1 });
|
|
53
|
+
expect(hits.length).toBe(1);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('returns empty array when no token overlap', async () => {
|
|
57
|
+
const a = new KnowledgeMemoryAdapter();
|
|
58
|
+
await a.upsert(docs, { source });
|
|
59
|
+
const hits = await a.search('xyzzy plugh', { source, topK: 5 });
|
|
60
|
+
expect(hits).toEqual([]);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('filters by metadata', async () => {
|
|
64
|
+
const a = new KnowledgeMemoryAdapter();
|
|
65
|
+
await a.upsert(docs, { source });
|
|
66
|
+
const hits = await a.search('fox', { source, topK: 5, filter: { topic: 'policy' } });
|
|
67
|
+
expect(hits.find((h) => h.documentId === 'd1')).toBeUndefined();
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it('delete removes a document', async () => {
|
|
71
|
+
const a = new KnowledgeMemoryAdapter();
|
|
72
|
+
await a.upsert(docs, { source });
|
|
73
|
+
await a.delete(['d2'], { source });
|
|
74
|
+
const hits = await a.search('refund', { source, topK: 5 });
|
|
75
|
+
expect(hits.find((h) => h.documentId === 'd2')).toBeUndefined();
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('upsert replaces existing chunks for the same doc', async () => {
|
|
79
|
+
const a = new KnowledgeMemoryAdapter();
|
|
80
|
+
await a.upsert(docs, { source });
|
|
81
|
+
await a.upsert(
|
|
82
|
+
[{ id: 'd2', sourceId: 'src1', content: 'Pineapples are tropical fruit.', title: 'New' }],
|
|
83
|
+
{ source },
|
|
84
|
+
);
|
|
85
|
+
const hits = await a.search('refund', { source, topK: 5 });
|
|
86
|
+
expect(hits.find((h) => h.documentId === 'd2')).toBeUndefined();
|
|
87
|
+
const tropical = await a.search('pineapple tropical', { source, topK: 5 });
|
|
88
|
+
expect(tropical[0]?.documentId).toBe('d2');
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('chunks long documents (snippet bounded)', async () => {
|
|
92
|
+
const a = new KnowledgeMemoryAdapter();
|
|
93
|
+
const long = 'lorem ipsum dolor sit amet '.repeat(200);
|
|
94
|
+
await a.upsert([{ id: 'long', sourceId: 'src1', content: long }], { source });
|
|
95
|
+
const hits = await a.search('lorem', { source, topK: 10 });
|
|
96
|
+
expect(hits.length).toBeGreaterThan(1);
|
|
97
|
+
for (const h of hits) expect(h.snippet.length).toBeLessThanOrEqual(900);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it('healthCheck returns ok', async () => {
|
|
101
|
+
const a = new KnowledgeMemoryAdapter();
|
|
102
|
+
const h = await a.healthCheck();
|
|
103
|
+
expect(h.ok).toBe(true);
|
|
104
|
+
});
|
|
105
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import type {
|
|
4
|
+
IKnowledgeAdapter,
|
|
5
|
+
IKnowledgeService,
|
|
6
|
+
AdapterContext,
|
|
7
|
+
AdapterSearchOptions,
|
|
8
|
+
} from '@objectstack/spec/contracts';
|
|
9
|
+
import type {
|
|
10
|
+
KnowledgeDocument,
|
|
11
|
+
KnowledgeHit,
|
|
12
|
+
} from '@objectstack/spec/ai';
|
|
13
|
+
import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* In-memory knowledge adapter. Stores per-source document maps,
|
|
17
|
+
* chunks documents naively on paragraph boundaries (with a soft 800-char
|
|
18
|
+
* cap), embeds each chunk as a sparse token-frequency vector, and
|
|
19
|
+
* answers `search()` via brute-force cosine similarity.
|
|
20
|
+
*
|
|
21
|
+
* Deterministic — same input always produces the same hits — so it's
|
|
22
|
+
* great for tests and reference implementations. **Don't use in prod.**
|
|
23
|
+
*/
|
|
24
|
+
export class KnowledgeMemoryAdapter implements IKnowledgeAdapter {
|
|
25
|
+
readonly id: string;
|
|
26
|
+
private readonly store = new Map<string, ChunkRecord[]>();
|
|
27
|
+
|
|
28
|
+
constructor(id = 'memory') {
|
|
29
|
+
this.id = id;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise<void> {
|
|
33
|
+
const sourceId = ctx.source.id;
|
|
34
|
+
const existing = this.store.get(sourceId) ?? [];
|
|
35
|
+
const byDoc = new Map<string, ChunkRecord[]>();
|
|
36
|
+
for (const c of existing) {
|
|
37
|
+
const arr = byDoc.get(c.documentId) ?? [];
|
|
38
|
+
arr.push(c);
|
|
39
|
+
byDoc.set(c.documentId, arr);
|
|
40
|
+
}
|
|
41
|
+
for (const doc of docs) {
|
|
42
|
+
byDoc.set(doc.id, chunkAndEmbed(doc));
|
|
43
|
+
}
|
|
44
|
+
this.store.set(sourceId, Array.from(byDoc.values()).flat());
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async delete(documentIds: string[], ctx: AdapterContext): Promise<void> {
|
|
48
|
+
const sourceId = ctx.source.id;
|
|
49
|
+
const chunks = this.store.get(sourceId);
|
|
50
|
+
if (!chunks) return;
|
|
51
|
+
const dropSet = new Set(documentIds);
|
|
52
|
+
this.store.set(
|
|
53
|
+
sourceId,
|
|
54
|
+
chunks.filter((c) => !dropSet.has(c.documentId)),
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async search(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]> {
|
|
59
|
+
const chunks = this.store.get(opts.source.id) ?? [];
|
|
60
|
+
if (chunks.length === 0) return [];
|
|
61
|
+
const qVec = embedTokens(tokenize(query));
|
|
62
|
+
const qNorm = vectorNorm(qVec);
|
|
63
|
+
if (qNorm === 0) return [];
|
|
64
|
+
|
|
65
|
+
const filter = opts.filter ?? {};
|
|
66
|
+
const filtered = Object.keys(filter).length
|
|
67
|
+
? chunks.filter((c) => matchesFilter(c.metadata, filter))
|
|
68
|
+
: chunks;
|
|
69
|
+
|
|
70
|
+
const scored = filtered.map((c) => ({
|
|
71
|
+
chunk: c,
|
|
72
|
+
score: cosineSimilarity(qVec, c.vector, qNorm, c.vectorNorm),
|
|
73
|
+
}));
|
|
74
|
+
scored.sort((a, b) => b.score - a.score);
|
|
75
|
+
const top = scored.slice(0, opts.topK).filter((s) => s.score > 0);
|
|
76
|
+
return top.map<KnowledgeHit>(({ chunk, score }) => ({
|
|
77
|
+
chunkId: chunk.chunkId,
|
|
78
|
+
documentId: chunk.documentId,
|
|
79
|
+
sourceId: opts.source.id,
|
|
80
|
+
sourceRecordId: chunk.sourceRecordId,
|
|
81
|
+
score,
|
|
82
|
+
snippet: chunk.content,
|
|
83
|
+
title: chunk.title,
|
|
84
|
+
metadata: chunk.metadata,
|
|
85
|
+
}));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async healthCheck(): Promise<{ ok: boolean; message?: string }> {
|
|
89
|
+
return { ok: true, message: `memory adapter (${this.store.size} sources)` };
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface ChunkRecord {
|
|
94
|
+
chunkId: string;
|
|
95
|
+
documentId: string;
|
|
96
|
+
sourceRecordId?: string;
|
|
97
|
+
content: string;
|
|
98
|
+
title?: string;
|
|
99
|
+
metadata: Record<string, unknown>;
|
|
100
|
+
vector: Map<string, number>;
|
|
101
|
+
vectorNorm: number;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const CHUNK_TARGET = 800;
|
|
105
|
+
|
|
106
|
+
function chunkAndEmbed(doc: KnowledgeDocument): ChunkRecord[] {
|
|
107
|
+
const paragraphs = doc.content
|
|
108
|
+
.split(/\n{2,}/)
|
|
109
|
+
.map((p) => p.trim())
|
|
110
|
+
.filter(Boolean);
|
|
111
|
+
const chunks: string[] = [];
|
|
112
|
+
let buf = '';
|
|
113
|
+
for (const p of paragraphs.length ? paragraphs : [doc.content]) {
|
|
114
|
+
if (buf && buf.length + p.length + 2 > CHUNK_TARGET) {
|
|
115
|
+
chunks.push(buf);
|
|
116
|
+
buf = '';
|
|
117
|
+
}
|
|
118
|
+
if (p.length > CHUNK_TARGET) {
|
|
119
|
+
if (buf) {
|
|
120
|
+
chunks.push(buf);
|
|
121
|
+
buf = '';
|
|
122
|
+
}
|
|
123
|
+
for (let i = 0; i < p.length; i += CHUNK_TARGET) {
|
|
124
|
+
chunks.push(p.slice(i, i + CHUNK_TARGET));
|
|
125
|
+
}
|
|
126
|
+
} else {
|
|
127
|
+
buf = buf ? `${buf}\n\n${p}` : p;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (buf) chunks.push(buf);
|
|
131
|
+
return chunks.map((content, idx) => {
|
|
132
|
+
const vec = embedTokens(tokenize(content));
|
|
133
|
+
return {
|
|
134
|
+
chunkId: `${doc.id}#${idx}`,
|
|
135
|
+
documentId: doc.id,
|
|
136
|
+
sourceRecordId: doc.sourceRecordId,
|
|
137
|
+
content,
|
|
138
|
+
title: doc.title,
|
|
139
|
+
metadata: doc.metadata ?? {},
|
|
140
|
+
vector: vec,
|
|
141
|
+
vectorNorm: vectorNorm(vec),
|
|
142
|
+
};
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function tokenize(text: string): string[] {
|
|
147
|
+
return text
|
|
148
|
+
.toLowerCase()
|
|
149
|
+
.split(/[^a-z0-9\u4e00-\u9fff]+/i)
|
|
150
|
+
.filter((t) => t.length > 1);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function embedTokens(tokens: string[]): Map<string, number> {
|
|
154
|
+
const vec = new Map<string, number>();
|
|
155
|
+
for (const t of tokens) vec.set(t, (vec.get(t) ?? 0) + 1);
|
|
156
|
+
return vec;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function vectorNorm(v: Map<string, number>): number {
|
|
160
|
+
let s = 0;
|
|
161
|
+
for (const x of v.values()) s += x * x;
|
|
162
|
+
return Math.sqrt(s);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function cosineSimilarity(
|
|
166
|
+
a: Map<string, number>,
|
|
167
|
+
b: Map<string, number>,
|
|
168
|
+
aNorm = vectorNorm(a),
|
|
169
|
+
bNorm = vectorNorm(b),
|
|
170
|
+
): number {
|
|
171
|
+
if (aNorm === 0 || bNorm === 0) return 0;
|
|
172
|
+
// iterate smaller map
|
|
173
|
+
const [small, big] = a.size < b.size ? [a, b] : [b, a];
|
|
174
|
+
let dot = 0;
|
|
175
|
+
for (const [k, v] of small) {
|
|
176
|
+
const w = big.get(k);
|
|
177
|
+
if (w) dot += v * w;
|
|
178
|
+
}
|
|
179
|
+
return dot / (aNorm * bNorm);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function matchesFilter(
|
|
183
|
+
metadata: Record<string, unknown>,
|
|
184
|
+
filter: Record<string, unknown>,
|
|
185
|
+
): boolean {
|
|
186
|
+
for (const [k, v] of Object.entries(filter)) {
|
|
187
|
+
if (metadata[k] !== v) return false;
|
|
188
|
+
}
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/* ---------------------------------------------------------------- */
|
|
193
|
+
/* Kernel plugin glue */
|
|
194
|
+
/* ---------------------------------------------------------------- */
|
|
195
|
+
|
|
196
|
+
import type { Plugin, PluginContext } from '@objectstack/core';
|
|
197
|
+
|
|
198
|
+
export interface KnowledgeMemoryPluginOptions {
|
|
199
|
+
/** Adapter id. @default 'memory' */
|
|
200
|
+
id?: string;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* `KnowledgeMemoryPlugin` — registers a `KnowledgeMemoryAdapter` with
|
|
205
|
+
* the host's `IKnowledgeService` during `start()`.
|
|
206
|
+
*/
|
|
207
|
+
export class KnowledgeMemoryPlugin implements Plugin {
|
|
208
|
+
name = 'com.objectstack.plugin.knowledge-memory';
|
|
209
|
+
version = '0.1.0';
|
|
210
|
+
type = 'standard';
|
|
211
|
+
|
|
212
|
+
private readonly adapter: KnowledgeMemoryAdapter;
|
|
213
|
+
|
|
214
|
+
constructor(opts: KnowledgeMemoryPluginOptions = {}) {
|
|
215
|
+
this.adapter = new KnowledgeMemoryAdapter(opts.id ?? 'memory');
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async init(_ctx: PluginContext): Promise<void> {
|
|
219
|
+
// No-op: registration happens in start() once IKnowledgeService is up.
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async start(ctx: PluginContext): Promise<void> {
|
|
223
|
+
let svc: IKnowledgeService | undefined;
|
|
224
|
+
try {
|
|
225
|
+
svc = ctx.getService<IKnowledgeService>(KNOWLEDGE_SERVICE);
|
|
226
|
+
} catch {
|
|
227
|
+
ctx.logger.warn?.(
|
|
228
|
+
'KnowledgeMemoryPlugin: IKnowledgeService not registered — install KnowledgeServicePlugin first.',
|
|
229
|
+
);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
svc.registerAdapter(this.adapter.id, this.adapter);
|
|
233
|
+
ctx.logger.info?.(`KnowledgeMemoryPlugin: adapter '${this.adapter.id}' registered.`);
|
|
234
|
+
}
|
|
235
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "../../../tsconfig.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"target": "ES2020",
|
|
5
|
+
"module": "ES2020",
|
|
6
|
+
"moduleResolution": "bundler",
|
|
7
|
+
"declaration": true,
|
|
8
|
+
"outDir": "./dist",
|
|
9
|
+
"strict": true,
|
|
10
|
+
"esModuleInterop": true,
|
|
11
|
+
"skipLibCheck": true,
|
|
12
|
+
"noUnusedLocals": false,
|
|
13
|
+
"noUnusedParameters": false,
|
|
14
|
+
"forceConsistentCasingInFileNames": true,
|
|
15
|
+
"types": ["node"],
|
|
16
|
+
"rootDir": "./src"
|
|
17
|
+
},
|
|
18
|
+
"include": ["src/**/*"],
|
|
19
|
+
"exclude": ["node_modules", "dist"]
|
|
20
|
+
}
|
package/vitest.config.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import { defineConfig } from 'vitest/config';
|
|
4
|
+
import path from 'path';
|
|
5
|
+
|
|
6
|
+
export default defineConfig({
|
|
7
|
+
test: {
|
|
8
|
+
globals: true,
|
|
9
|
+
environment: 'node',
|
|
10
|
+
},
|
|
11
|
+
resolve: {
|
|
12
|
+
alias: {
|
|
13
|
+
'@objectstack/core': path.resolve(__dirname, '../../core/src/index.ts'),
|
|
14
|
+
'@objectstack/service-knowledge': path.resolve(__dirname, '../../services/service-knowledge/src/index.ts'),
|
|
15
|
+
'@objectstack/spec/ai': path.resolve(__dirname, '../../spec/src/ai/index.ts'),
|
|
16
|
+
'@objectstack/spec/contracts': path.resolve(__dirname, '../../spec/src/contracts/index.ts'),
|
|
17
|
+
'@objectstack/spec/data': path.resolve(__dirname, '../../spec/src/data/index.ts'),
|
|
18
|
+
'@objectstack/spec/kernel': path.resolve(__dirname, '../../spec/src/kernel/index.ts'),
|
|
19
|
+
'@objectstack/spec/system': path.resolve(__dirname, '../../spec/src/system/index.ts'),
|
|
20
|
+
'@objectstack/spec': path.resolve(__dirname, '../../spec/src/index.ts'),
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
});
|