@loomwork/memory 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/NOTICE +8 -0
- package/README.md +79 -2
- package/dist/InMemoryMemoryStore.d.ts +26 -0
- package/dist/InMemoryMemoryStore.d.ts.map +1 -0
- package/dist/InMemoryMemoryStore.js +82 -0
- package/dist/InMemoryMemoryStore.js.map +1 -0
- package/dist/MemoryRuntime.d.ts +49 -0
- package/dist/MemoryRuntime.d.ts.map +1 -0
- package/dist/MemoryRuntime.js +144 -0
- package/dist/MemoryRuntime.js.map +1 -0
- package/dist/TieredMemory.d.ts +114 -0
- package/dist/TieredMemory.d.ts.map +1 -0
- package/dist/TieredMemory.js +165 -0
- package/dist/TieredMemory.js.map +1 -0
- package/dist/embedding.d.ts +174 -0
- package/dist/embedding.d.ts.map +1 -0
- package/dist/embedding.js +568 -0
- package/dist/embedding.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +30 -0
- package/dist/index.js.map +1 -0
- package/dist/searchText.d.ts +51 -0
- package/dist/searchText.d.ts.map +1 -0
- package/dist/searchText.js +142 -0
- package/dist/searchText.js.map +1 -0
- package/dist/types.d.ts +170 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +78 -0
- package/dist/types.js.map +1 -0
- package/package.json +54 -3
- package/src/InMemoryMemoryStore.ts +79 -0
- package/src/MemoryRuntime.ts +155 -0
- package/src/TieredMemory.ts +247 -0
- package/src/embedding.ts +655 -0
- package/src/index.ts +38 -0
- package/src/searchText.ts +141 -0
- package/src/types.ts +207 -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 must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,80 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @loomwork/memory — agent memory
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Scoped memory for agents and flows: ordered lists of entries kept outside the event log, addressed by a
|
|
4
|
+
memory id plus a scope (an execution, a conversation, a user). `MemoryRuntime` applies each memory's TTL
|
|
5
|
+
and size limits, `TieredMemory` adds named tiers with their own policy plus promotion between them, and
|
|
6
|
+
the `MemoryStore` interface is what a backend (SQLite, Postgres, a vector store) implements. Use it
|
|
7
|
+
directly when you want recency or relevance recall inside a flow; `defineConfig` already builds one
|
|
8
|
+
`MemoryRuntime` for `app.memory` over its `memoryStore` option.
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import {
|
|
12
|
+
DEFAULT_TIERS,
|
|
13
|
+
EmbeddingMemoryStore,
|
|
14
|
+
HashingEmbeddingProvider,
|
|
15
|
+
InMemoryMemoryStore,
|
|
16
|
+
TieredMemory,
|
|
17
|
+
} from "@loomwork/memory";
|
|
18
|
+
import type { ExecutionContext } from "@loomwork/workflow-runtime";
|
|
19
|
+
|
|
20
|
+
// Any MemoryStore works; wrapping one in EmbeddingMemoryStore makes `search` semantic.
|
|
21
|
+
// HashingEmbeddingProvider is the offline reference (lexical overlap only): swap in a real model.
|
|
22
|
+
const store = new EmbeddingMemoryStore({
|
|
23
|
+
store: new InMemoryMemoryStore(),
|
|
24
|
+
provider: new HashingEmbeddingProvider(),
|
|
25
|
+
minScore: 0.2, // required: cosine is defined against every entry, so "matches" needs a floor
|
|
26
|
+
});
|
|
27
|
+
const memory = new TieredMemory({ tiers: DEFAULT_TIERS, store });
|
|
28
|
+
|
|
29
|
+
await memory.remember("episodic", "user-42", { role: "user", content: "prefers metric units" });
|
|
30
|
+
const recent = await memory.recall("episodic", "user-42", { limit: 5 }); // newest N
|
|
31
|
+
|
|
32
|
+
// Inside a flow, pass ctx.decide: the retrieved set is recorded, so a replay is served the same entries.
|
|
33
|
+
export async function relevantFacts(ctx: ExecutionContext, question: string) {
|
|
34
|
+
return memory.recallRelevant("semantic", "user-42", question, { decide: ctx.decide });
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Surface
|
|
39
|
+
|
|
40
|
+
- **Runtime.** `MemoryRuntime` (`register`, `append`, `read`, `clear`, `remove`, `search`) keyed by
|
|
41
|
+
`(memoryId, scope)`; definitions come from `memory$({ id, name, ttlMs, maxEntries })` in `@loomwork/core`.
|
|
42
|
+
- **Tiers.** `TieredMemory` (`remember`, `recall`, `recallRelevant`, `promote`, `summarize`, `forget`,
|
|
43
|
+
`clear`) and `DEFAULT_TIERS`: `working` (`summarizeAfter: 20`), `episodic` (`maxEntries: 200`),
|
|
44
|
+
`semantic` and `procedural` (no eviction). A tier policy is `ttlMs`, `maxEntries` or `summarizeAfter`.
|
|
45
|
+
- **Stores.** `InMemoryMemoryStore` (default; lost on restart). Durable ones are `SqliteMemoryStore`
|
|
46
|
+
(`@loomwork/plugin-sqlite`) and `PostgresMemoryStore` (`@loomwork/plugin-postgres`).
|
|
47
|
+
- **Backend contract.** `MemoryStore` needs `append`, `read`, `clear`; `replace`, `search`, `remove` and
|
|
48
|
+
`close` are optional. Also `MEMORY_STORE_SPI_VERSION` (2.1.0), `searchableText`, `tokenize`,
|
|
49
|
+
`queryTerms` / `MAX_QUERY_TERMS`, `clampSearchLimit` with `DEFAULT_SEARCH_LIMIT` and `MAX_SEARCH_LIMIT`.
|
|
50
|
+
`runMemoryStoreConformance` in `@loomwork/conformance` proves a backend.
|
|
51
|
+
- **Embeddings (ADR 0124).** `EmbeddingMemoryStore`, the `EmbeddingProvider` and `VectorIndex` interfaces,
|
|
52
|
+
`InMemoryVectorIndex`, `HashingEmbeddingProvider`, `cosine`, `EmbeddingError`,
|
|
53
|
+
`EmbeddingModelMismatchError`, `MemoryIndexTooLargeError`.
|
|
54
|
+
|
|
55
|
+
## Behaviour that surprises people
|
|
56
|
+
|
|
57
|
+
- **Relevance recall needs `search`.** `MemoryRuntime.search` throws if the store has none, and
|
|
58
|
+
`recallRelevant` takes a required `decide` so what reached the prompt is a recorded fact. To search
|
|
59
|
+
without recording (an ops lookup, a test), call the store's `search` directly.
|
|
60
|
+
- **TTL is applied after the store's `limit`**, so a search over an expiring memory can return fewer than
|
|
61
|
+
`limit` hits. `read` persists the pruned list; `search` does not.
|
|
62
|
+
- **Reads are in append order**, not timestamp order, and an absent key reads as `[]`.
|
|
63
|
+
- **`forget` and `clear` are not recorded.** Only recall goes through `decide`.
|
|
64
|
+
- **Entry `id` is not indexed.** It is caller metadata that every backend must round-trip; `content` is
|
|
65
|
+
what `searchableText` projects.
|
|
66
|
+
- **A tier that evicts cannot hold a corpus.** `@loomwork/knowledge` refuses `ttlMs` / `maxEntries` tiers for
|
|
67
|
+
that reason.
|
|
68
|
+
- **An embedding failure on `append` to an already-indexed key means the append is not made**, so the
|
|
69
|
+
store and its index do not silently disagree.
|
|
70
|
+
|
|
71
|
+
## Install
|
|
72
|
+
|
|
73
|
+
Unpublished for now: inside this repo use `workspace:*`; from a sibling checkout use a `link:` override (see [AGENTS.md](../../AGENTS.md)).
|
|
74
|
+
|
|
75
|
+
## See also
|
|
76
|
+
|
|
77
|
+
- API reference: section "`@loomwork/memory` — agent memory" in [docs/api-reference.org](../../docs/api-reference.org).
|
|
78
|
+
- Guides: [user guide, section 16: tiered memory](../../docs/user-guide.md#16-tiered-memory), [reasoning and memory](../../docs/loom-2.0/02-reasoning-and-memory.md).
|
|
79
|
+
- ADRs: [0033 SPI conformance](../../docs/adr/0033-spi-conformance-contracts.md), [0090 knowledge is retrieval over memory](../../docs/adr/0090-knowledge-is-retrieval-over-memory.md), [0124 learning lifecycle](../../docs/adr/0124-learning-lifecycle.md) (embeddings).
|
|
80
|
+
- Source: `packages/memory/src`. Retrieval over documents: [`@loomwork/knowledge`](../knowledge/README.md).
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { MemoryEntry, MemorySearchOptions, MemoryStore } from "./types";
|
|
2
|
+
export declare class InMemoryMemoryStore implements MemoryStore {
|
|
3
|
+
private readonly entries;
|
|
4
|
+
append(key: string, entry: MemoryEntry): Promise<void>;
|
|
5
|
+
read(key: string): Promise<MemoryEntry[]>;
|
|
6
|
+
clear(key: string): Promise<void>;
|
|
7
|
+
/**
|
|
8
|
+
* Remove by id in one pass with a Set membership test — O(entries + ids), not
|
|
9
|
+
* O(entries x ids), because a corpus removal names every chunk of a document at once.
|
|
10
|
+
*
|
|
11
|
+
* Rebuilds the list rather than splicing: `read` hands out the stored array itself,
|
|
12
|
+
* so mutating it in place would edit a list a caller may still be holding.
|
|
13
|
+
*/
|
|
14
|
+
remove(key: string, ids: readonly string[]): Promise<void>;
|
|
15
|
+
/**
|
|
16
|
+
* Reference relevance search: sum of the IDF of the query terms an entry contains,
|
|
17
|
+
* ties broken by recency. Deliberately simple and deliberately NOT a hidden search
|
|
18
|
+
* engine — it exists so `recallRelevant` works on the default store and so the kit
|
|
19
|
+
* runs against three independent rankers rather than one implementation twice. IDF
|
|
20
|
+
* (rather than a raw match count) is what stops a term present in every entry from
|
|
21
|
+
* deciding the order; a real corpus belongs in SqliteMemoryStore/PostgresMemoryStore,
|
|
22
|
+
* whose indexes do this properly and without scanning.
|
|
23
|
+
*/
|
|
24
|
+
search(key: string, query: string, opts?: MemorySearchOptions): Promise<MemoryEntry[]>;
|
|
25
|
+
}
|
|
26
|
+
//# sourceMappingURL=InMemoryMemoryStore.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"InMemoryMemoryStore.d.ts","sourceRoot":"","sources":["../src/InMemoryMemoryStore.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAE7E,qBAAa,mBAAoB,YAAW,WAAW;IACrD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAoC;IAEtD,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IAMtD,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAIzC,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIvC;;;;;;OAMG;IACG,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAWhE;;;;;;;;OAQG;IACG,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,GAAE,mBAAwB,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;CA8BjG"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.InMemoryMemoryStore = void 0;
|
|
4
|
+
const searchText_1 = require("./searchText");
|
|
5
|
+
const types_1 = require("./types");
|
|
6
|
+
class InMemoryMemoryStore {
|
|
7
|
+
entries = new Map();
|
|
8
|
+
async append(key, entry) {
|
|
9
|
+
const list = this.entries.get(key) ?? [];
|
|
10
|
+
list.push(entry);
|
|
11
|
+
this.entries.set(key, list);
|
|
12
|
+
}
|
|
13
|
+
async read(key) {
|
|
14
|
+
return this.entries.get(key) ?? [];
|
|
15
|
+
}
|
|
16
|
+
async clear(key) {
|
|
17
|
+
this.entries.delete(key);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Remove by id in one pass with a Set membership test — O(entries + ids), not
|
|
21
|
+
* O(entries x ids), because a corpus removal names every chunk of a document at once.
|
|
22
|
+
*
|
|
23
|
+
* Rebuilds the list rather than splicing: `read` hands out the stored array itself,
|
|
24
|
+
* so mutating it in place would edit a list a caller may still be holding.
|
|
25
|
+
*/
|
|
26
|
+
async remove(key, ids) {
|
|
27
|
+
if (ids.length === 0)
|
|
28
|
+
return;
|
|
29
|
+
const list = this.entries.get(key);
|
|
30
|
+
if (list === undefined)
|
|
31
|
+
return;
|
|
32
|
+
const doomed = new Set(ids);
|
|
33
|
+
const kept = list.filter((entry) => entry.id === undefined || !doomed.has(entry.id));
|
|
34
|
+
if (kept.length === list.length)
|
|
35
|
+
return;
|
|
36
|
+
if (kept.length === 0)
|
|
37
|
+
this.entries.delete(key);
|
|
38
|
+
else
|
|
39
|
+
this.entries.set(key, kept);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Reference relevance search: sum of the IDF of the query terms an entry contains,
|
|
43
|
+
* ties broken by recency. Deliberately simple and deliberately NOT a hidden search
|
|
44
|
+
* engine — it exists so `recallRelevant` works on the default store and so the kit
|
|
45
|
+
* runs against three independent rankers rather than one implementation twice. IDF
|
|
46
|
+
* (rather than a raw match count) is what stops a term present in every entry from
|
|
47
|
+
* deciding the order; a real corpus belongs in SqliteMemoryStore/PostgresMemoryStore,
|
|
48
|
+
* whose indexes do this properly and without scanning.
|
|
49
|
+
*/
|
|
50
|
+
async search(key, query, opts = {}) {
|
|
51
|
+
const terms = new Set((0, searchText_1.queryTerms)(query));
|
|
52
|
+
const entries = this.entries.get(key) ?? [];
|
|
53
|
+
if (terms.size === 0 || entries.length === 0)
|
|
54
|
+
return [];
|
|
55
|
+
// One pass to the document-frequency table, one to score: O(entries × terms).
|
|
56
|
+
const documents = entries.map((entry) => new Set((0, searchText_1.tokenize)((0, searchText_1.searchableText)(entry))));
|
|
57
|
+
const documentFrequency = new Map();
|
|
58
|
+
for (const document of documents) {
|
|
59
|
+
for (const term of terms) {
|
|
60
|
+
if (document.has(term))
|
|
61
|
+
documentFrequency.set(term, (documentFrequency.get(term) ?? 0) + 1);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const scored = [];
|
|
65
|
+
for (const [index, document] of documents.entries()) {
|
|
66
|
+
let score = 0;
|
|
67
|
+
for (const term of terms) {
|
|
68
|
+
const frequency = documentFrequency.get(term);
|
|
69
|
+
if (frequency !== undefined && document.has(term)) {
|
|
70
|
+
score += Math.log(1 + entries.length / frequency);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (score > 0)
|
|
74
|
+
scored.push({ entry: entries[index], index, score });
|
|
75
|
+
}
|
|
76
|
+
// Descending score; a tie goes to the more recently appended entry.
|
|
77
|
+
scored.sort((a, b) => b.score - a.score || b.index - a.index);
|
|
78
|
+
return scored.slice(0, (0, types_1.clampSearchLimit)(opts.limit)).map((s) => s.entry);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
exports.InMemoryMemoryStore = InMemoryMemoryStore;
|
|
82
|
+
//# sourceMappingURL=InMemoryMemoryStore.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"InMemoryMemoryStore.js","sourceRoot":"","sources":["../src/InMemoryMemoryStore.ts"],"names":[],"mappings":";;;AAAA,6CAAoE;AACpE,mCAA2C;AAG3C,MAAa,mBAAmB;IACb,OAAO,GAAG,IAAI,GAAG,EAAyB,CAAC;IAE5D,KAAK,CAAC,MAAM,CAAC,GAAW,EAAE,KAAkB;QAC1C,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;QACzC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACjB,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAC9B,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,GAAW;QACpB,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;IACrC,CAAC;IAED,KAAK,CAA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EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;QAC9D,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,IAAA,wBAAgB,EAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;IAC3E,CAAC;CACF;AA1ED,kDA0EC"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { MemoryDefinition } from "@loomwork/core";
|
|
2
|
+
import type { MemoryEntry, MemorySearchOptions, MemoryStore } from "./types";
|
|
3
|
+
export declare class MemoryRuntime {
|
|
4
|
+
private readonly store;
|
|
5
|
+
private readonly definitions;
|
|
6
|
+
constructor(store?: MemoryStore);
|
|
7
|
+
register(definition: MemoryDefinition): this;
|
|
8
|
+
/**
|
|
9
|
+
* The registered definition for a memory id, or `undefined`.
|
|
10
|
+
*
|
|
11
|
+
* Exposed for the same reason as `TieredMemory.tierPolicy`: a caller that is about to
|
|
12
|
+
* write data whose correctness depends on the WHOLE set being present needs to know
|
|
13
|
+
* whether something else has registered an eviction policy over the same key space.
|
|
14
|
+
* Two runtimes can share one store, and only the one that reads applies its own policy.
|
|
15
|
+
*/
|
|
16
|
+
definitionFor(memoryId: string): MemoryDefinition | undefined;
|
|
17
|
+
private key;
|
|
18
|
+
append(memoryId: string, scope: string, entry: Omit<MemoryEntry, "timestamp"> & {
|
|
19
|
+
timestamp?: number;
|
|
20
|
+
}): Promise<void>;
|
|
21
|
+
read(memoryId: string, scope: string): Promise<MemoryEntry[]>;
|
|
22
|
+
clear(memoryId: string, scope: string): Promise<void>;
|
|
23
|
+
/**
|
|
24
|
+
* Remove specific entries by {@link MemoryEntry.id}, keeping the rest of the scope.
|
|
25
|
+
*
|
|
26
|
+
* Unlike `search`, an absent backend verb here does NOT fail: the fallback —
|
|
27
|
+
* read, filter, rewrite — is CORRECT, just linear in the scope, so refusing would
|
|
28
|
+
* deny a working capability rather than prevent a silent wrong answer. (That is the
|
|
29
|
+
* whole distinction: there is no read-based way to fake relevance retrieval, and
|
|
30
|
+
* there is an obvious read-based way to delete.)
|
|
31
|
+
*
|
|
32
|
+
* The rewrite goes through `persist`, so it inherits atomic `replace` where the
|
|
33
|
+
* backend has one — the same durability argument as eviction: a crash between
|
|
34
|
+
* `clear` and the re-appends would lose the scope this call was asked to prune.
|
|
35
|
+
*/
|
|
36
|
+
remove(memoryId: string, scope: string, ids: readonly string[]): Promise<void>;
|
|
37
|
+
/**
|
|
38
|
+
* Retrieve by relevance instead of by recency. Requires a store that implements the
|
|
39
|
+
* optional `search`; a store without one FAILS LOUDLY rather than falling back to
|
|
40
|
+
* `read`, because a silent fallback would hand back the tail of the scope while the
|
|
41
|
+
* caller believed it had retrieved — the kind of degradation nothing downstream can
|
|
42
|
+
* detect, and which shows up only as worse answers.
|
|
43
|
+
*/
|
|
44
|
+
search(memoryId: string, scope: string, query: string, opts?: MemorySearchOptions): Promise<MemoryEntry[]>;
|
|
45
|
+
private pruneList;
|
|
46
|
+
private persist;
|
|
47
|
+
private evict;
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=MemoryRuntime.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"MemoryRuntime.d.ts","sourceRoot":"","sources":["../src/MemoryRuntime.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAO7E,qBAAa,aAAa;IAGZ,OAAO,CAAC,QAAQ,CAAC,KAAK;IAFlC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAuC;gBAEtC,KAAK,GAAE,WAAuC;IAE3E,QAAQ,CAAC,UAAU,EAAE,gBAAgB,GAAG,IAAI;IAK5C;;;;;;;OAOG;IACH,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS;IAI7D,OAAO,CAAC,GAAG;IAIL,MAAM,CACV,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,IAAI,CAAC,WAAW,EAAE,WAAW,CAAC,GAAG;QAAE,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,GAC7D,OAAO,CAAC,IAAI,CAAC;IAMV,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAW7D,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI3D;;;;;;;;;;;;OAYG;IACG,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAapF;;;;;;OAMG;IACG,MAAM,CACV,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,IAAI,GAAE,mBAAwB,GAC7B,OAAO,CAAC,WAAW,EAAE,CAAC;IAoBzB,OAAO,CAAC,SAAS;YAmBH,OAAO;YAUP,KAAK;CAOpB"}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MemoryRuntime = void 0;
|
|
4
|
+
const InMemoryMemoryStore_1 = require("./InMemoryMemoryStore");
|
|
5
|
+
// The Agent Runtime's "memory access" from the proposal. A MemoryRuntime holds
|
|
6
|
+
// named memories (registered from memory$() definitions) and enforces each
|
|
7
|
+
// memory's ttlMs / maxEntries policy on read and write. Memory is addressed by
|
|
8
|
+
// (memoryId, scope) — scope is typically an executionId, conversationId, or
|
|
9
|
+
// userId, letting one memory definition serve many concurrent sessions.
|
|
10
|
+
class MemoryRuntime {
|
|
11
|
+
store;
|
|
12
|
+
definitions = new Map();
|
|
13
|
+
constructor(store = new InMemoryMemoryStore_1.InMemoryMemoryStore()) {
|
|
14
|
+
this.store = store;
|
|
15
|
+
}
|
|
16
|
+
register(definition) {
|
|
17
|
+
this.definitions.set(definition.id, definition);
|
|
18
|
+
return this;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The registered definition for a memory id, or `undefined`.
|
|
22
|
+
*
|
|
23
|
+
* Exposed for the same reason as `TieredMemory.tierPolicy`: a caller that is about to
|
|
24
|
+
* write data whose correctness depends on the WHOLE set being present needs to know
|
|
25
|
+
* whether something else has registered an eviction policy over the same key space.
|
|
26
|
+
* Two runtimes can share one store, and only the one that reads applies its own policy.
|
|
27
|
+
*/
|
|
28
|
+
definitionFor(memoryId) {
|
|
29
|
+
return this.definitions.get(memoryId);
|
|
30
|
+
}
|
|
31
|
+
key(memoryId, scope) {
|
|
32
|
+
return `${memoryId}::${scope}`;
|
|
33
|
+
}
|
|
34
|
+
async append(memoryId, scope, entry) {
|
|
35
|
+
const key = this.key(memoryId, scope);
|
|
36
|
+
await this.store.append(key, { ...entry, timestamp: entry.timestamp ?? Date.now() });
|
|
37
|
+
await this.evict(memoryId, key);
|
|
38
|
+
}
|
|
39
|
+
async read(memoryId, scope) {
|
|
40
|
+
const key = this.key(memoryId, scope);
|
|
41
|
+
const stored = await this.store.read(key);
|
|
42
|
+
const pruned = this.pruneList(memoryId, stored);
|
|
43
|
+
// Lazy expiry: if the view dropped entries, persist it so a cold scope (read but never
|
|
44
|
+
// re-appended) doesn't retain stale entries — and a scope pruned to empty drops its key
|
|
45
|
+
// entirely (clear + no re-append), bounding the store's distinct-scope growth.
|
|
46
|
+
if (pruned.length !== stored.length)
|
|
47
|
+
await this.persist(key, pruned);
|
|
48
|
+
return pruned;
|
|
49
|
+
}
|
|
50
|
+
async clear(memoryId, scope) {
|
|
51
|
+
await this.store.clear(this.key(memoryId, scope));
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Remove specific entries by {@link MemoryEntry.id}, keeping the rest of the scope.
|
|
55
|
+
*
|
|
56
|
+
* Unlike `search`, an absent backend verb here does NOT fail: the fallback —
|
|
57
|
+
* read, filter, rewrite — is CORRECT, just linear in the scope, so refusing would
|
|
58
|
+
* deny a working capability rather than prevent a silent wrong answer. (That is the
|
|
59
|
+
* whole distinction: there is no read-based way to fake relevance retrieval, and
|
|
60
|
+
* there is an obvious read-based way to delete.)
|
|
61
|
+
*
|
|
62
|
+
* The rewrite goes through `persist`, so it inherits atomic `replace` where the
|
|
63
|
+
* backend has one — the same durability argument as eviction: a crash between
|
|
64
|
+
* `clear` and the re-appends would lose the scope this call was asked to prune.
|
|
65
|
+
*/
|
|
66
|
+
async remove(memoryId, scope, ids) {
|
|
67
|
+
if (ids.length === 0)
|
|
68
|
+
return;
|
|
69
|
+
const key = this.key(memoryId, scope);
|
|
70
|
+
if (this.store.remove !== undefined) {
|
|
71
|
+
await this.store.remove(key, ids);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const stored = await this.store.read(key);
|
|
75
|
+
const doomed = new Set(ids);
|
|
76
|
+
const kept = stored.filter((entry) => entry.id === undefined || !doomed.has(entry.id));
|
|
77
|
+
if (kept.length !== stored.length)
|
|
78
|
+
await this.persist(key, kept);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Retrieve by relevance instead of by recency. Requires a store that implements the
|
|
82
|
+
* optional `search`; a store without one FAILS LOUDLY rather than falling back to
|
|
83
|
+
* `read`, because a silent fallback would hand back the tail of the scope while the
|
|
84
|
+
* caller believed it had retrieved — the kind of degradation nothing downstream can
|
|
85
|
+
* detect, and which shows up only as worse answers.
|
|
86
|
+
*/
|
|
87
|
+
async search(memoryId, scope, query, opts = {}) {
|
|
88
|
+
if (this.store.search === undefined) {
|
|
89
|
+
throw new Error(`memory "${memoryId}": the configured MemoryStore does not implement search(). Use a backend that does (SqliteMemoryStore, PostgresMemoryStore, InMemoryMemoryStore), or recall by recency with read().`);
|
|
90
|
+
}
|
|
91
|
+
const hits = await this.store.search(this.key(memoryId, scope), query, opts);
|
|
92
|
+
// TTL applies to a hit as much as to a read — an expired entry reaching a prompt is
|
|
93
|
+
// the bug TTL exists to prevent. Filtered AFTER the store's `limit`, so an expiring
|
|
94
|
+
// tier can return fewer than `limit` rows; the alternative is reading the whole scope
|
|
95
|
+
// to prune it, which is exactly what an index is for. NOT persisted: unlike `read`,
|
|
96
|
+
// these entries are an arbitrary subset, and rewriting the list from a subset would
|
|
97
|
+
// delete everything that did not match.
|
|
98
|
+
const def = this.definitions.get(memoryId);
|
|
99
|
+
if (def?.ttlMs === undefined)
|
|
100
|
+
return hits;
|
|
101
|
+
const cutoff = Date.now() - def.ttlMs;
|
|
102
|
+
return hits.filter((e) => e.timestamp >= cutoff);
|
|
103
|
+
}
|
|
104
|
+
// Drop entries older than ttlMs, then keep only the newest maxEntries. Pure.
|
|
105
|
+
pruneList(memoryId, entries) {
|
|
106
|
+
const def = this.definitions.get(memoryId);
|
|
107
|
+
let out = entries;
|
|
108
|
+
if (def?.ttlMs !== undefined) {
|
|
109
|
+
const cutoff = Date.now() - def.ttlMs;
|
|
110
|
+
out = out.filter((e) => e.timestamp >= cutoff);
|
|
111
|
+
}
|
|
112
|
+
if (def?.maxEntries !== undefined && out.length > def.maxEntries) {
|
|
113
|
+
out = out.slice(out.length - def.maxEntries);
|
|
114
|
+
}
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
// Rewrite the stored list to `entries` (empty ⇒ the key is dropped).
|
|
118
|
+
//
|
|
119
|
+
// Prefers the store's atomic `replace` when it has one: on a durable backend the
|
|
120
|
+
// clear-then-re-append fallback is a window in which eviction — the routine path —
|
|
121
|
+
// can lose the whole scope to a crash. The fallback is still the contract for
|
|
122
|
+
// backends without it (including the in-memory default, which has no crash to lose).
|
|
123
|
+
async persist(key, entries) {
|
|
124
|
+
if (this.store.replace !== undefined) {
|
|
125
|
+
await this.store.replace(key, entries);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
await this.store.clear(key);
|
|
129
|
+
for (const entry of entries)
|
|
130
|
+
await this.store.append(key, entry);
|
|
131
|
+
}
|
|
132
|
+
// Rewrite the stored list to the pruned view so eviction is durable (only when it changed).
|
|
133
|
+
async evict(memoryId, key) {
|
|
134
|
+
const def = this.definitions.get(memoryId);
|
|
135
|
+
if (def?.ttlMs === undefined && def?.maxEntries === undefined)
|
|
136
|
+
return;
|
|
137
|
+
const stored = await this.store.read(key);
|
|
138
|
+
const pruned = this.pruneList(memoryId, stored);
|
|
139
|
+
if (pruned.length !== stored.length)
|
|
140
|
+
await this.persist(key, pruned);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
exports.MemoryRuntime = MemoryRuntime;
|
|
144
|
+
//# sourceMappingURL=MemoryRuntime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"MemoryRuntime.js","sourceRoot":"","sources":["../src/MemoryRuntime.ts"],"names":[],"mappings":";;;AACA,+DAA4D;AAG5D,+EAA+E;AAC/E,2EAA2E;AAC3E,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,MAAa,aAAa;IAGK;IAFZ,WAAW,GAAG,IAAI,GAAG,EAA4B,CAAC;IAEnE,YAA6B,QAAqB,IAAI,yCAAmB,EAAE;QAA9C,UAAK,GAAL,KAAK,CAAyC;IAAG,CAAC;IAE/E,QAAQ,CAAC,UAA4B;QACnC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,EAAE,UAAU,CAAC,CAAC;QAChD,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;;;;;OAOG;IACH,aAAa,CAAC,QAAgB;QAC5B,OAAO,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC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