@amaster.ai/pi-memory 0.1.2-beta.11

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 ADDED
@@ -0,0 +1,201 @@
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.
package/README.md ADDED
@@ -0,0 +1,129 @@
1
+ # @amaster.ai/pi-memory
2
+
3
+ Persistent curated memory for pi agents — `MEMORY.md` (the agent's own notes) and `USER.md` (what the agent knows about the user). Both are loaded from disk at session start, **frozen**, and injected into the system prompt for the entire session. Mid-session writes are durable on disk but do **not** mutate the system prompt — this preserves prefix-cache stability.
4
+
5
+ Modeled after hermes' default `MemoryStore` mechanism (no provider/manager abstraction).
6
+
7
+ ## Storage
8
+
9
+ - Location: `<agentDir>/memories/MEMORY.md` and `<agentDir>/memories/USER.md`
10
+ - Entries separated by `\n§\n`
11
+ - Atomic writes via temp-file + rename
12
+ - Read-modify-write protected by `proper-lockfile`
13
+ - **Drift detection**: if the on-disk file contains content that wouldn't round-trip through the parser/serializer (or any single entry exceeds the per-store char limit), the mutation is refused and a `.bak.<unix-ts>` snapshot is taken for the user to recover from.
14
+
15
+ ## Safety
16
+
17
+ Every write — and every system-prompt snapshot build — runs the content through the bundled `threat-patterns` scanner at the `strict` scope. Patterns cover prompt injection, role hijack, C2 framework names, exfiltration, persistence (SSH backdoor, agent-config edits), and invisible unicode.
18
+
19
+ | Action | On match |
20
+ |----------------------|-----------------------------------------------------------------------------------------------------------|
21
+ | `memory_add` / `memory_replace` | Reject with the matched pattern id; live state and disk unchanged. |
22
+ | Snapshot build (load) | Replace the entry with `[BLOCKED: <filename> entry contained threat pattern(s): <ids>...]`. The poisoned content **never** enters the system prompt. Live state keeps the original so `memory_read` / `memory_remove` can recover. |
23
+
24
+ ## Tools
25
+
26
+ Four LLM-callable tools (separate, not action-multiplexed):
27
+
28
+ | Tool | Purpose |
29
+ |------------------|--------------------------------------------------------------------------|
30
+ | `memory_add` | Append a new entry. Rejects empty / duplicate / over-limit / threat content. |
31
+ | `memory_replace` | Update an existing entry by short unique substring (`oldText`). |
32
+ | `memory_remove` | Delete an entry by short unique substring (`oldText`). |
33
+ | `memory_read` | Return live entries, count, and `<percent>% — <chars>/<limit>` usage string. |
34
+
35
+ `target` is `'memory'` (the agent's own notes) or `'user'` (user profile facts).
36
+
37
+ ## Defaults
38
+
39
+ | Store | Char limit |
40
+ |----------|------------|
41
+ | MEMORY | 2200 |
42
+ | USER | 1375 |
43
+
44
+ These are total chars after `§`-joining all entries. The limit is enforced at write time, and at load time as a drift signal (single-entry overflow).
45
+
46
+ ## Integration Modes
47
+
48
+ ### Mode 1: Extension auto-discovery (standalone / CLI)
49
+
50
+ When installed as a dependency with the `pi.extensions` field declared in `package.json`, the runtime auto-discovers and loads the extension. The extension creates its own `MemoryStore` with file-based storage at `<agentDir>/memories/` — fully self-contained.
51
+
52
+ ```
53
+ pi.extensions → session_start → load MEMORY.md/USER.md → freeze snapshot → register tools
54
+ → before_agent_start → append snapshot to systemPrompt
55
+ → session_shutdown → release
56
+ ```
57
+
58
+ - **Storage**: `<agentDir>/memories/MEMORY.md` and `<agentDir>/memories/USER.md`
59
+ - **Lifecycle**: load on `session_start`, snapshot held until `session_shutdown`
60
+ - **Status command**: `/pi-memory-status` shows entry counts per file
61
+ - **LLM tools**: `memory_add`, `memory_replace`, `memory_remove`, `memory_read`
62
+
63
+ Configure via the `pi-memory` settings key:
64
+
65
+ ```json
66
+ {
67
+ "pi-memory": {
68
+ "dataDir": "/custom/memory/path",
69
+ "memoryCharLimit": 4000,
70
+ "userCharLimit": 2000
71
+ }
72
+ }
73
+ ```
74
+
75
+ ### Mode 2: Dependency import (host-controlled)
76
+
77
+ When the host process owns the `MemoryStore` (e.g. shared across agents, test fixtures, custom storage path), construct the store yourself and register tools directly:
78
+
79
+ ```ts
80
+ import { MemoryStore, createMemoryTools } from "@amaster.ai/pi-memory";
81
+
82
+ const store = new MemoryStore({
83
+ dir: "/var/lib/pi/agent-42/memories",
84
+ memoryCharLimit: 4000,
85
+ });
86
+ await store.loadFromDisk();
87
+
88
+ // ToolDefinition[] — wire into your tool registry directly
89
+ const tools = createMemoryTools(store);
90
+
91
+ // System prompt fragment (frozen at loadFromDisk; safe to use repeatedly)
92
+ const promptBlock = store.formatAllForSystemPrompt();
93
+ ```
94
+
95
+ You can also pass a pre-built store into the extension via `injectedConfig` to keep the extension lifecycle but use your own storage:
96
+
97
+ ```ts
98
+ import memoryExtension from "@amaster.ai/pi-memory";
99
+
100
+ memoryExtension(pi, { store });
101
+ ```
102
+
103
+ ## Drift recovery
104
+
105
+ If `memory_add` / `memory_replace` / `memory_remove` returns `success: false` with `driftBackup: ".../MEMORY.md.bak.<ts>"`, the on-disk file no longer round-trips through the parser. This usually means a patch tool / shell append / manual edit / concurrent session wrote raw content that broke the `§`-delimited structure.
106
+
107
+ To recover:
108
+
109
+ 1. Open the `.bak.<ts>` snapshot and identify content not yet captured as clean entries.
110
+ 2. Add each missing entry via `memory_add`.
111
+ 3. Either delete the original `MEMORY.md` (the next add will recreate it) or rewrite it as a clean `§`-delimited list.
112
+
113
+ The drift guard exists to prevent silent data loss — never bypass it by deleting `.bak.<ts>` snapshots blindly.
114
+
115
+ ## Frozen snapshot
116
+
117
+ `loadFromDisk()` captures the system-prompt block once; subsequent `add` / `replace` / `remove` calls update **live state** but not the snapshot. Why:
118
+
119
+ - The system prompt is the prefix-cache key for every model call. Mutating it mid-session invalidates the entire prefix.
120
+ - Tool responses always reflect live state, so the model still sees its own writes — just via tool-result tail, not system-prompt head.
121
+ - The snapshot picks up changes on the **next** `loadFromDisk()` (typically the next session start).
122
+
123
+ ## Lifecycle reference
124
+
125
+ | Hook | Behavior |
126
+ |-----------------------|---------------------------------------------------------------------------|
127
+ | `session_start` | Resolve `dataDir`, build `MemoryStore`, `loadFromDisk()`, capture snapshot, register 4 tools, set status `memory: loaded`/`memory: empty`. |
128
+ | `before_agent_start` | Append snapshot to assembled `systemPrompt` (no-op when empty). |
129
+ | `session_shutdown` | Drop store + snapshot references. |
@@ -0,0 +1,14 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
+ import { MemoryStore } from './store.js';
3
+ export type PiMemoryExtensionConfig = {
4
+ /** Directory containing MEMORY.md / USER.md. Default: `<agentDir>/memories`. */
5
+ dataDir?: string;
6
+ /** Char limit for MEMORY.md. Default 2200. */
7
+ memoryCharLimit?: number;
8
+ /** Char limit for USER.md. Default 1375. */
9
+ userCharLimit?: number;
10
+ /** Pre-built store (host-controlled mode). */
11
+ store?: MemoryStore;
12
+ };
13
+ export default function memoryExtension(pi: ExtensionAPI, injectedConfig?: PiMemoryExtensionConfig): void;
14
+ //# sourceMappingURL=extension.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension.d.ts","sourceRoot":"","sources":["../src/extension.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAoBzC,MAAM,MAAM,uBAAuB,GAAG;IACpC,gFAAgF;IAChF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,8CAA8C;IAC9C,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,4CAA4C;IAC5C,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,8CAA8C;IAC9C,KAAK,CAAC,EAAE,WAAW,CAAC;CACrB,CAAC;AA+BF,MAAM,CAAC,OAAO,UAAU,eAAe,CACrC,EAAE,EAAE,YAAY,EAChB,cAAc,CAAC,EAAE,uBAAuB,GACvC,IAAI,CA8DN"}
@@ -0,0 +1,98 @@
1
+ import path from 'node:path';
2
+ import { loadPiSettings, resolveAgentDir } from '@amaster.ai/pi-shared/settings';
3
+ import { MemoryStore } from './store.js';
4
+ import { createMemoryTools } from './tools.js';
5
+ const SETTINGS_KEY = 'pi-memory';
6
+ const STATUS_KEY = 'pi-memory';
7
+ const MEMORY_GUIDANCE = [
8
+ '## Memory Guidance',
9
+ '',
10
+ 'You have persistent memory across sessions via the memory_add / memory_replace / memory_remove / memory_read tools.',
11
+ 'Save durable facts: user preferences, environment details, tool quirks, and stable conventions.',
12
+ 'Memory is injected into every turn, so keep it compact and focused on facts that will still matter later.',
13
+ '',
14
+ 'Prioritize what reduces future user steering — the most valuable memory is one that prevents the user from having to correct or remind you again. User preferences and recurring corrections matter more than procedural task details.',
15
+ '',
16
+ "Do NOT save task progress, session outcomes, completed-work logs, or temporary TODO state. Specifically: do not record PR numbers, issue numbers, commit SHAs, 'fixed bug X', 'submitted PR Y', 'Phase N done', file counts, or any artifact that will be stale in 7 days. If a fact will be stale in a week, it does not belong in memory.",
17
+ '',
18
+ "Write memories as declarative facts, not instructions to yourself. 'User prefers concise responses' ✓ — 'Always respond concisely' ✗. 'Project uses pytest with xdist' ✓ — 'Run tests with pytest -n 4' ✗. Imperative phrasing gets re-read as a directive in later sessions and can cause repeated work or override the user's current request.",
19
+ ].join('\n');
20
+ function resolveConfig(raw) {
21
+ const resolved = {
22
+ dataDir: raw?.dataDir?.trim() || path.join(resolveAgentDir(), 'memories'),
23
+ };
24
+ if (raw?.memoryCharLimit !== undefined)
25
+ resolved.memoryCharLimit = raw.memoryCharLimit;
26
+ if (raw?.userCharLimit !== undefined)
27
+ resolved.userCharLimit = raw.userCharLimit;
28
+ if (raw?.store)
29
+ resolved.store = raw.store;
30
+ return resolved;
31
+ }
32
+ function loadSettings(cwd) {
33
+ try {
34
+ const config = loadPiSettings(SETTINGS_KEY, {
35
+ cwd,
36
+ agentDir: resolveAgentDir(),
37
+ });
38
+ return Object.keys(config).length > 0 ? config : undefined;
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ }
44
+ export default function memoryExtension(pi, injectedConfig) {
45
+ let store;
46
+ let snapshot = '';
47
+ pi.on('session_start', async (_event, ctx) => {
48
+ const fileConfig = loadSettings(ctx.cwd);
49
+ const config = resolveConfig({ ...fileConfig, ...injectedConfig });
50
+ try {
51
+ if (config.store) {
52
+ store = config.store;
53
+ }
54
+ else {
55
+ const opts = { dir: config.dataDir };
56
+ if (config.memoryCharLimit !== undefined)
57
+ opts.memoryCharLimit = config.memoryCharLimit;
58
+ if (config.userCharLimit !== undefined)
59
+ opts.userCharLimit = config.userCharLimit;
60
+ store = new MemoryStore(opts);
61
+ }
62
+ await store.loadFromDisk();
63
+ snapshot = store.formatAllForSystemPrompt();
64
+ ctx.ui.setStatus(STATUS_KEY, snapshot ? 'memory: loaded' : 'memory: empty');
65
+ for (const tool of createMemoryTools(store)) {
66
+ pi.registerTool(tool);
67
+ }
68
+ }
69
+ catch (err) {
70
+ ctx.ui.setStatus(STATUS_KEY, 'memory: unavailable');
71
+ // Surface as a notification only — registration failure shouldn't crash the session.
72
+ ctx.ui.notify(`pi-memory failed to initialize: ${err instanceof Error ? err.message : String(err)}`, 'error');
73
+ }
74
+ });
75
+ pi.on('before_agent_start', async (event) => {
76
+ const block = snapshot ? `${MEMORY_GUIDANCE}\n\n${snapshot}` : MEMORY_GUIDANCE;
77
+ return {
78
+ systemPrompt: event.systemPrompt ? `${event.systemPrompt}\n\n${block}` : block,
79
+ };
80
+ });
81
+ pi.on('session_shutdown', async () => {
82
+ store = undefined;
83
+ snapshot = '';
84
+ });
85
+ pi.registerCommand('pi-memory-status', {
86
+ description: 'Show pi-memory status (entry counts and char usage).',
87
+ handler: async (_args, ctx) => {
88
+ if (!store) {
89
+ ctx.ui.notify('pi-memory is not loaded.', 'warning');
90
+ return;
91
+ }
92
+ const memEntries = store.getEntries('memory');
93
+ const userEntries = store.getEntries('user');
94
+ ctx.ui.notify(`MEMORY.md: ${memEntries.length} entries\nUSER.md: ${userEntries.length} entries`, 'info');
95
+ },
96
+ });
97
+ }
98
+ //# sourceMappingURL=extension.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension.js","sourceRoot":"","sources":["../src/extension.ts"],"names":[],"mappings":"AAAA,OAAO,IA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AC;YAC9C,MAAM,WAAW,GAAG,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;YAC7C,GAAG,CAAC,EAAE,CAAC,MAAM,CACX,cAAc,UAAU,CAAC,MAAM,sBAAsB,WAAW,CAAC,MAAM,UAAU,EACjF,MAAM,CACP,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,6 @@
1
+ export { default } from './extension.js';
2
+ export type { MemoryDriftError, MemoryErrorResult, MemoryResult, MemoryStoreOptions, MemorySuccessResult, MemoryTarget, } from './store.js';
3
+ export { ENTRY_DELIMITER, MemoryStore } from './store.js';
4
+ export { firstThreatMessage, INVISIBLE_CHARS, scanForThreats } from './threat-patterns.js';
5
+ export { createMemoryTools } from './tools.js';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AACzC,YAAY,EACV,gBAAgB,EAChB,iBAAiB,EACjB,YAAY,EACZ,kBAAkB,EAClB,mBAAmB,EACnB,YAAY,GACb,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3F,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { default } from './extension.js';
2
+ export { ENTRY_DELIMITER, MemoryStore } from './store.js';
3
+ export { firstThreatMessage, INVISIBLE_CHARS, scanForThreats } from './threat-patterns.js';
4
+ export { createMemoryTools } from './tools.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AASzC,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3F,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC"}
@@ -0,0 +1,91 @@
1
+ export declare const ENTRY_DELIMITER = "\n\u00A7\n";
2
+ export type MemoryTarget = 'memory' | 'user';
3
+ export type MemoryStoreOptions = {
4
+ /** Directory where MEMORY.md and USER.md live. */
5
+ dir: string;
6
+ /** Char limit for MEMORY.md. Default 2200. */
7
+ memoryCharLimit?: number;
8
+ /** Char limit for USER.md. Default 1375. */
9
+ userCharLimit?: number;
10
+ };
11
+ export type MemorySuccessResult = {
12
+ success: true;
13
+ target: MemoryTarget;
14
+ entries: string[];
15
+ usage: string;
16
+ entryCount: number;
17
+ message?: string;
18
+ };
19
+ export type MemoryDriftError = {
20
+ success: false;
21
+ error: string;
22
+ driftBackup: string;
23
+ remediation: string;
24
+ };
25
+ export type MemoryErrorResult = {
26
+ success: false;
27
+ error: string;
28
+ matches?: string[];
29
+ currentEntries?: string[];
30
+ usage?: string;
31
+ };
32
+ export type MemoryResult = MemorySuccessResult | MemoryDriftError | MemoryErrorResult;
33
+ /**
34
+ * Bounded curated memory with file persistence.
35
+ *
36
+ * Two parallel states:
37
+ * - `_systemPromptSnapshot`: frozen at `loadFromDisk()`, used for system
38
+ * prompt injection. Never mutated mid-session — keeps prefix cache stable.
39
+ * - `memoryEntries` / `userEntries`: live state, mutated by tool calls,
40
+ * persisted to disk. Tool responses always reflect this live state.
41
+ */
42
+ export declare class MemoryStore {
43
+ readonly dir: string;
44
+ readonly memoryCharLimit: number;
45
+ readonly userCharLimit: number;
46
+ private memoryEntries;
47
+ private userEntries;
48
+ private systemPromptSnapshot;
49
+ private loaded;
50
+ constructor(opts: MemoryStoreOptions);
51
+ /**
52
+ * Load entries from MEMORY.md and USER.md, capture system prompt snapshot.
53
+ *
54
+ * Each entry is scanned for injection / promptware patterns at strict
55
+ * scope; ANY match replaces the entry text in the snapshot with a
56
+ * `[BLOCKED: …]` placeholder so a poisoned-on-disk file (supply chain,
57
+ * compromised tool, sister-session write) cannot enter the system
58
+ * prompt. Live state keeps the original so the user can inspect and
59
+ * remove via `memory_read` / `memory_remove`.
60
+ */
61
+ loadFromDisk(): Promise<void>;
62
+ /** Return frozen snapshot for system prompt injection. Empty string if no entries. */
63
+ formatForSystemPrompt(target: MemoryTarget): string;
64
+ /** Combined memory + user snapshot block, with a blank line between them. */
65
+ formatAllForSystemPrompt(): string;
66
+ /** Live entries, not the frozen snapshot. */
67
+ getEntries(target: MemoryTarget): string[];
68
+ add(target: MemoryTarget, content: string): Promise<MemoryResult>;
69
+ replace(target: MemoryTarget, oldText: string, newContent: string): Promise<MemoryResult>;
70
+ remove(target: MemoryTarget, oldText: string): Promise<MemoryResult>;
71
+ read(target: MemoryTarget): Promise<MemorySuccessResult>;
72
+ private pathFor;
73
+ private entriesFor;
74
+ private setEntries;
75
+ private charLimit;
76
+ private charCount;
77
+ private successResponse;
78
+ private renderBlock;
79
+ private saveToDisk;
80
+ /**
81
+ * Re-read entries from disk. Returns backup-path string when external
82
+ * drift was detected (the on-disk file contains content that wouldn't
83
+ * round-trip through the parser/serializer, OR an entry larger than the
84
+ * store's char limit). Caller must abort the mutation when drift is
85
+ * detected — flushing would discard the un-roundtrippable content.
86
+ */
87
+ private reloadTarget;
88
+ private detectExternalDrift;
89
+ private withFileLock;
90
+ }
91
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,eAAe,eAAU,CAAC;AAEvC,MAAM,MAAM,YAAY,GAAG,QAAQ,GAAG,MAAM,CAAC;AAE7C,MAAM,MAAM,kBAAkB,GAAG;I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