warm-claude-tool 0.1.0__tar.gz
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.
- warm_claude_tool-0.1.0/.gitignore +6 -0
- warm_claude_tool-0.1.0/LICENSE +201 -0
- warm_claude_tool-0.1.0/PKG-INFO +66 -0
- warm_claude_tool-0.1.0/README.md +50 -0
- warm_claude_tool-0.1.0/pyproject.toml +34 -0
- warm_claude_tool-0.1.0/src/warm_memory_tool/__init__.py +34 -0
- warm_claude_tool-0.1.0/src/warm_memory_tool/core.py +328 -0
- warm_claude_tool-0.1.0/src/warm_memory_tool/paths.py +67 -0
- warm_claude_tool-0.1.0/src/warm_memory_tool/store.py +247 -0
- warm_claude_tool-0.1.0/src/warm_memory_tool/tool.py +208 -0
|
@@ -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.
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: warm-claude-tool
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Backend for Anthropic's client-side memory tool (memory_20250818) on WARM: a /memories virtual filesystem with semantic recall.
|
|
5
|
+
Project-URL: Homepage, https://github.com/writerslogic/warm/tree/main/docs/integrations/claude-memory-tool
|
|
6
|
+
Project-URL: Repository, https://github.com/writerslogic/warm
|
|
7
|
+
Project-URL: Issues, https://github.com/writerslogic/warm/issues
|
|
8
|
+
Author-email: "WritersLogic, Inc." <david@writerslogic.com>
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: agent-memory,anthropic,claude,local-first,mcp,memory-tool
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Requires-Dist: anthropic>=1.16
|
|
14
|
+
Requires-Dist: mcp<3,>=2.3
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# warm-claude-tool (Python)
|
|
18
|
+
|
|
19
|
+
Backs Anthropic's client-side memory tool (`memory_20250818`) with WARM: Claude's `/memories` directory is stored in a `warm-mcp` server and every file is searchable by meaning.
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
pip install warm-claude-tool # plus a warm-mcp binary: npx -y writerslogic-warm-mcp, or uvx warm-mcp
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Quickstart
|
|
28
|
+
|
|
29
|
+
<!-- quickstart-check: skip: requires API key (ANTHROPIC_API_KEY) -->
|
|
30
|
+
```python
|
|
31
|
+
import anthropic
|
|
32
|
+
from warm_memory_tool import WarmMemoryToolSync
|
|
33
|
+
|
|
34
|
+
client = anthropic.Anthropic()
|
|
35
|
+
with WarmMemoryToolSync.connect(command="warm-mcp") as memory: # or url="http://127.0.0.1:8765/mcp"
|
|
36
|
+
runner = client.beta.messages.tool_runner(
|
|
37
|
+
model="claude-sonnet-5-5",
|
|
38
|
+
max_tokens=1024,
|
|
39
|
+
messages=[{"role": "user", "content": "Remember that Acme Corp prefers email follow-ups."}],
|
|
40
|
+
tools=[memory, memory.recall_tool()],
|
|
41
|
+
)
|
|
42
|
+
print(runner.until_done().content)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Needs `ANTHROPIC_API_KEY`, so it is not run by the docs check; the tool itself is tested offline against a real `warm-mcp` in `tests/`.
|
|
46
|
+
|
|
47
|
+
## Options
|
|
48
|
+
|
|
49
|
+
`WarmMemoryTool` (async, `BetaAsyncAbstractMemoryTool`) and `WarmMemoryToolSync` (`BetaAbstractMemoryTool`) take the same arguments to `connect(...)`.
|
|
50
|
+
|
|
51
|
+
| Name | Type | Default | Meaning |
|
|
52
|
+
|---|---|---|---|
|
|
53
|
+
| `command`, `args`, `env` | str, list, dict | none | Start `warm-mcp` over stdio |
|
|
54
|
+
| `url`, `token` | str, str | none, `WARM_MCP_TOKEN` | Connect to a shared `warm-mcp --transport http` |
|
|
55
|
+
| `namespace` | str | none | One store per user (server needs `--namespace-arg`) |
|
|
56
|
+
| `max_view_chars` | int | 16000 | Longest `view` result before paging with `view_range` |
|
|
57
|
+
| `edit_retries` | int | 25 | Compare-and-set retries when another writer edits the same file |
|
|
58
|
+
| `request_timeout` | float | 60.0 | Seconds per MCP request |
|
|
59
|
+
|
|
60
|
+
## Compatibility
|
|
61
|
+
|
|
62
|
+
Python 3.10+, `anthropic` >= 1.16, `mcp` 2.3 to <3, a `warm-mcp` server. Tested on Python 3.12 (31 tests against a real `warm-mcp`).
|
|
63
|
+
|
|
64
|
+
## Reference
|
|
65
|
+
|
|
66
|
+
Commands, safety rules and semantic recall: [Anthropic memory tool on WARM](https://github.com/writerslogic/warm/blob/main/docs/integrations/mcp/memory-tool.md). TypeScript sibling: [`../typescript`](../typescript/README.md).
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# warm-claude-tool (Python)
|
|
2
|
+
|
|
3
|
+
Backs Anthropic's client-side memory tool (`memory_20250818`) with WARM: Claude's `/memories` directory is stored in a `warm-mcp` server and every file is searchable by meaning.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pip install warm-claude-tool # plus a warm-mcp binary: npx -y writerslogic-warm-mcp, or uvx warm-mcp
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quickstart
|
|
12
|
+
|
|
13
|
+
<!-- quickstart-check: skip: requires API key (ANTHROPIC_API_KEY) -->
|
|
14
|
+
```python
|
|
15
|
+
import anthropic
|
|
16
|
+
from warm_memory_tool import WarmMemoryToolSync
|
|
17
|
+
|
|
18
|
+
client = anthropic.Anthropic()
|
|
19
|
+
with WarmMemoryToolSync.connect(command="warm-mcp") as memory: # or url="http://127.0.0.1:8765/mcp"
|
|
20
|
+
runner = client.beta.messages.tool_runner(
|
|
21
|
+
model="claude-sonnet-5-5",
|
|
22
|
+
max_tokens=1024,
|
|
23
|
+
messages=[{"role": "user", "content": "Remember that Acme Corp prefers email follow-ups."}],
|
|
24
|
+
tools=[memory, memory.recall_tool()],
|
|
25
|
+
)
|
|
26
|
+
print(runner.until_done().content)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Needs `ANTHROPIC_API_KEY`, so it is not run by the docs check; the tool itself is tested offline against a real `warm-mcp` in `tests/`.
|
|
30
|
+
|
|
31
|
+
## Options
|
|
32
|
+
|
|
33
|
+
`WarmMemoryTool` (async, `BetaAsyncAbstractMemoryTool`) and `WarmMemoryToolSync` (`BetaAbstractMemoryTool`) take the same arguments to `connect(...)`.
|
|
34
|
+
|
|
35
|
+
| Name | Type | Default | Meaning |
|
|
36
|
+
|---|---|---|---|
|
|
37
|
+
| `command`, `args`, `env` | str, list, dict | none | Start `warm-mcp` over stdio |
|
|
38
|
+
| `url`, `token` | str, str | none, `WARM_MCP_TOKEN` | Connect to a shared `warm-mcp --transport http` |
|
|
39
|
+
| `namespace` | str | none | One store per user (server needs `--namespace-arg`) |
|
|
40
|
+
| `max_view_chars` | int | 16000 | Longest `view` result before paging with `view_range` |
|
|
41
|
+
| `edit_retries` | int | 25 | Compare-and-set retries when another writer edits the same file |
|
|
42
|
+
| `request_timeout` | float | 60.0 | Seconds per MCP request |
|
|
43
|
+
|
|
44
|
+
## Compatibility
|
|
45
|
+
|
|
46
|
+
Python 3.10+, `anthropic` >= 1.16, `mcp` 2.3 to <3, a `warm-mcp` server. Tested on Python 3.12 (31 tests against a real `warm-mcp`).
|
|
47
|
+
|
|
48
|
+
## Reference
|
|
49
|
+
|
|
50
|
+
Commands, safety rules and semantic recall: [Anthropic memory tool on WARM](https://github.com/writerslogic/warm/blob/main/docs/integrations/mcp/memory-tool.md). TypeScript sibling: [`../typescript`](../typescript/README.md).
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Copyright 2024-2026 WritersLogic Contributors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
[build-system]
|
|
4
|
+
requires = ["hatchling>=1.27"]
|
|
5
|
+
build-backend = "hatchling.build"
|
|
6
|
+
|
|
7
|
+
[project]
|
|
8
|
+
name = "warm-claude-tool"
|
|
9
|
+
version = "0.1.0"
|
|
10
|
+
description = "Backend for Anthropic's client-side memory tool (memory_20250818) on WARM: a /memories virtual filesystem with semantic recall."
|
|
11
|
+
readme = "README.md"
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
license = "Apache-2.0"
|
|
14
|
+
license-files = ["LICENSE"]
|
|
15
|
+
authors = [{ name = "WritersLogic, Inc.", email = "david@writerslogic.com" }]
|
|
16
|
+
keywords = ["anthropic", "claude", "memory-tool", "mcp", "agent-memory", "local-first"]
|
|
17
|
+
dependencies = ["anthropic>=1.16", "mcp>=2.3,<3"]
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Homepage = "https://github.com/writerslogic/warm/tree/main/docs/integrations/claude-memory-tool"
|
|
21
|
+
Repository = "https://github.com/writerslogic/warm"
|
|
22
|
+
Issues = "https://github.com/writerslogic/warm/issues"
|
|
23
|
+
|
|
24
|
+
[dependency-groups]
|
|
25
|
+
dev = ["pytest>=8", "anyio[trio]>=4"]
|
|
26
|
+
|
|
27
|
+
[tool.hatch.build.targets.sdist]
|
|
28
|
+
include = ["src/warm_memory_tool", "README.md", "LICENSE"]
|
|
29
|
+
|
|
30
|
+
[tool.hatch.build.targets.wheel]
|
|
31
|
+
packages = ["src/warm_memory_tool"]
|
|
32
|
+
|
|
33
|
+
[tool.pytest.ini_options]
|
|
34
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Copyright 2024-2026 WritersLogic Contributors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Anthropic memory tool (memory_20250818) backend on WARM."""
|
|
4
|
+
|
|
5
|
+
from .core import MemoryFs, MemoryToolFailure
|
|
6
|
+
from .paths import ROOT, MemoryPathError, normalize_path
|
|
7
|
+
from .store import (
|
|
8
|
+
ConflictError,
|
|
9
|
+
FileEntry,
|
|
10
|
+
FileStore,
|
|
11
|
+
WarmToolError,
|
|
12
|
+
McpFileStore,
|
|
13
|
+
RecallHit,
|
|
14
|
+
StoredFile,
|
|
15
|
+
)
|
|
16
|
+
from .tool import WarmMemoryTool, WarmMemoryToolSync
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"ROOT",
|
|
20
|
+
"ConflictError",
|
|
21
|
+
"FileEntry",
|
|
22
|
+
"FileStore",
|
|
23
|
+
"WarmToolError",
|
|
24
|
+
"WarmMemoryTool",
|
|
25
|
+
"WarmMemoryToolSync",
|
|
26
|
+
"McpFileStore",
|
|
27
|
+
"MemoryFs",
|
|
28
|
+
"MemoryPathError",
|
|
29
|
+
"MemoryToolFailure",
|
|
30
|
+
"RecallHit",
|
|
31
|
+
"StoredFile",
|
|
32
|
+
"normalize_path",
|
|
33
|
+
]
|
|
34
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
# Copyright 2024-2026 WritersLogic Contributors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The six memory_20250818 commands over a `FileStore`, with the result strings the documented
|
|
4
|
+
reference behaviour uses, plus semantic recall. Framework-agnostic: errors are `MemoryToolFailure`."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import math
|
|
10
|
+
import random
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Optional, Sequence
|
|
13
|
+
|
|
14
|
+
from .paths import MemoryPathError, ROOT, ancestors, is_inside, normalize_path
|
|
15
|
+
from .store import ConflictError, FileEntry, FileStore, WarmToolError
|
|
16
|
+
|
|
17
|
+
LINE_NUMBER_WIDTH = 6
|
|
18
|
+
MAX_LINES = 999_999
|
|
19
|
+
LISTING_DEPTH = 2
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class MemoryToolFailure(Exception):
|
|
23
|
+
"""A failure to report to Claude as an error tool result."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def human_size(size: int) -> str:
|
|
27
|
+
if size == 0:
|
|
28
|
+
return "0B"
|
|
29
|
+
units = ["B", "K", "M", "G"]
|
|
30
|
+
i = min(int(math.log2(size)) // 10, len(units) - 1)
|
|
31
|
+
value = size / (1024**i)
|
|
32
|
+
return f"{int(value)}{units[i]}" if value == int(value) else f"{value:.1f}{units[i]}"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def numbered(lines: Sequence[str], start: int) -> str:
|
|
36
|
+
return "\n".join(f"{str(i + start).rjust(LINE_NUMBER_WIDTH)}\t{line}" for i, line in enumerate(lines))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def split_lines(text: str) -> list[str]:
|
|
40
|
+
"""Lines of a file the way the tool counts them: a trailing newline adds no empty line."""
|
|
41
|
+
lines = text.split("\n")
|
|
42
|
+
if lines and lines[-1] == "":
|
|
43
|
+
lines.pop()
|
|
44
|
+
return lines
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class _Node:
|
|
49
|
+
name: str
|
|
50
|
+
bytes: int = 0
|
|
51
|
+
is_dir: bool = True
|
|
52
|
+
|
|
53
|
+
def __post_init__(self) -> None:
|
|
54
|
+
self.children: dict[str, _Node] = {}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class MemoryFs:
|
|
58
|
+
def __init__(self, store: FileStore, *, max_view_chars: int = 16_000, edit_retries: int = 25) -> None:
|
|
59
|
+
self.store = store
|
|
60
|
+
self.max_view_chars = max_view_chars
|
|
61
|
+
self.edit_retries = edit_retries
|
|
62
|
+
|
|
63
|
+
@staticmethod
|
|
64
|
+
def _path(path: object) -> str:
|
|
65
|
+
try:
|
|
66
|
+
return normalize_path(path)
|
|
67
|
+
except MemoryPathError as error:
|
|
68
|
+
raise MemoryToolFailure(str(error)) from error
|
|
69
|
+
|
|
70
|
+
async def _guard(self, call): # type: ignore[no-untyped-def]
|
|
71
|
+
try:
|
|
72
|
+
return await call
|
|
73
|
+
except WarmToolError as error:
|
|
74
|
+
raise MemoryToolFailure(str(error)) from error
|
|
75
|
+
|
|
76
|
+
async def _kind(self, path: str) -> str:
|
|
77
|
+
if path == ROOT:
|
|
78
|
+
return "dir"
|
|
79
|
+
if await self.store.get(path):
|
|
80
|
+
return "file"
|
|
81
|
+
return "dir" if await self.store.list(path + "/") else "none"
|
|
82
|
+
|
|
83
|
+
def _check_size(self, text: str) -> None:
|
|
84
|
+
size = len(text.encode())
|
|
85
|
+
if size > self.store.max_file_bytes:
|
|
86
|
+
raise MemoryToolFailure(
|
|
87
|
+
f"Error: the file would be {size} bytes; the limit is {self.store.max_file_bytes}. "
|
|
88
|
+
"Split the content into several files."
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
async def _check_creatable(self, path: str) -> None:
|
|
92
|
+
for ancestor in ancestors(path):
|
|
93
|
+
if await self.store.get(ancestor):
|
|
94
|
+
raise MemoryToolFailure(f"Error: {ancestor} is a file, so {path} cannot be created inside it")
|
|
95
|
+
if await self.store.list(path + "/"):
|
|
96
|
+
raise MemoryToolFailure(f"Error: {path} is a directory")
|
|
97
|
+
|
|
98
|
+
# ---- view ---------------------------------------------------------------------------
|
|
99
|
+
|
|
100
|
+
async def view(self, raw_path: str, view_range: Optional[Sequence[int]] = None) -> str:
|
|
101
|
+
path = self._path(raw_path)
|
|
102
|
+
file = None if path == ROOT else await self._guard(self.store.get(path))
|
|
103
|
+
if file is not None:
|
|
104
|
+
return self._view_file(path, file.text, view_range)
|
|
105
|
+
entries = await self._guard(self.store.list(path + "/"))
|
|
106
|
+
if not entries and path != ROOT:
|
|
107
|
+
raise MemoryToolFailure(f"The path {raw_path} does not exist. Please provide a valid path.")
|
|
108
|
+
return self._view_directory(path, entries)
|
|
109
|
+
|
|
110
|
+
def _view_file(self, path: str, text: str, view_range: Optional[Sequence[int]]) -> str:
|
|
111
|
+
lines = split_lines(text)
|
|
112
|
+
if len(lines) > MAX_LINES:
|
|
113
|
+
raise MemoryToolFailure(f"File {path} exceeds maximum line limit of 999,999 lines.")
|
|
114
|
+
start, shown = 1, lines
|
|
115
|
+
if view_range is not None and len(view_range) == 2:
|
|
116
|
+
first, last = view_range
|
|
117
|
+
if not isinstance(first, int) or not isinstance(last, int) or first < 1 or (last != -1 and last < first):
|
|
118
|
+
raise MemoryToolFailure(
|
|
119
|
+
f"Error: invalid view_range {list(view_range)}; use [start, end] with 1 <= start <= end, or end = -1"
|
|
120
|
+
)
|
|
121
|
+
start = first
|
|
122
|
+
shown = lines[first - 1 :] if last == -1 else lines[first - 1 : last]
|
|
123
|
+
header = f"Here's the content of {path} with line numbers:\n"
|
|
124
|
+
body = numbered(shown, start)
|
|
125
|
+
if len(header) + len(body) > self.max_view_chars:
|
|
126
|
+
kept: list[str] = []
|
|
127
|
+
size = len(header)
|
|
128
|
+
for i, line in enumerate(shown):
|
|
129
|
+
row = f"{str(i + start).rjust(LINE_NUMBER_WIDTH)}\t{line}"
|
|
130
|
+
if size + len(row) + 1 > self.max_view_chars and kept:
|
|
131
|
+
break
|
|
132
|
+
kept.append(row if len(row) <= self.max_view_chars else row[: self.max_view_chars - 200] + " [line truncated]")
|
|
133
|
+
size += len(row) + 1
|
|
134
|
+
body = (
|
|
135
|
+
"\n".join(kept)
|
|
136
|
+
+ f"\n[Output truncated at {self.max_view_chars} characters. "
|
|
137
|
+
f"Use view_range starting at line {start + len(kept)} to read the rest.]"
|
|
138
|
+
)
|
|
139
|
+
return header + body
|
|
140
|
+
|
|
141
|
+
def _view_directory(self, path: str, entries: Sequence[FileEntry]) -> str:
|
|
142
|
+
root = _Node("")
|
|
143
|
+
prefix = path + "/"
|
|
144
|
+
for entry in entries:
|
|
145
|
+
parts = entry.path[len(prefix) :].split("/")
|
|
146
|
+
node = root
|
|
147
|
+
node.bytes += entry.bytes
|
|
148
|
+
for i, part in enumerate(parts):
|
|
149
|
+
child = node.children.get(part)
|
|
150
|
+
if child is None:
|
|
151
|
+
child = node.children[part] = _Node(part, is_dir=i < len(parts) - 1)
|
|
152
|
+
child.bytes += entry.bytes
|
|
153
|
+
node = child
|
|
154
|
+
rows = [f"{human_size(root.bytes)}\t{path}"]
|
|
155
|
+
|
|
156
|
+
def walk(node: _Node, base: str, depth: int) -> None:
|
|
157
|
+
for child in sorted(node.children.values(), key=lambda c: c.name):
|
|
158
|
+
if child.name == "node_modules":
|
|
159
|
+
continue
|
|
160
|
+
shown = f"{base}/{child.name}"
|
|
161
|
+
rows.append(f"{human_size(child.bytes)}\t{shown}{'/' if child.is_dir else ''}")
|
|
162
|
+
if child.is_dir and depth < LISTING_DEPTH:
|
|
163
|
+
walk(child, shown, depth + 1)
|
|
164
|
+
|
|
165
|
+
walk(root, path, 1)
|
|
166
|
+
return (
|
|
167
|
+
f"Here're the files and directories up to 2 levels deep in {path}, "
|
|
168
|
+
"excluding hidden items and node_modules:\n" + "\n".join(rows)
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
# ---- create / edit ------------------------------------------------------------------
|
|
172
|
+
|
|
173
|
+
async def create(self, raw_path: str, file_text: str) -> str:
|
|
174
|
+
path = self._path(raw_path)
|
|
175
|
+
if path == ROOT:
|
|
176
|
+
raise MemoryToolFailure("Error: /memories is a directory")
|
|
177
|
+
self._check_size(file_text)
|
|
178
|
+
await self._guard(self._check_creatable(path))
|
|
179
|
+
try:
|
|
180
|
+
await self._guard(self.store.put(path, file_text, create_only=True))
|
|
181
|
+
except ConflictError as error:
|
|
182
|
+
if error.kind == "exists":
|
|
183
|
+
raise MemoryToolFailure(f"Error: File {raw_path} already exists") from error
|
|
184
|
+
raise
|
|
185
|
+
return f"File created successfully at: {raw_path}"
|
|
186
|
+
|
|
187
|
+
async def _edit(self, path: str, not_found: str, change) -> str: # type: ignore[no-untyped-def]
|
|
188
|
+
"""Read-modify-write with compare-and-set, retried when another writer got in between."""
|
|
189
|
+
for attempt in range(self.edit_retries):
|
|
190
|
+
file = await self._guard(self.store.get(path))
|
|
191
|
+
if file is None:
|
|
192
|
+
raise MemoryToolFailure(not_found)
|
|
193
|
+
text, result = change(file.text)
|
|
194
|
+
self._check_size(text)
|
|
195
|
+
try:
|
|
196
|
+
await self._guard(self.store.put(path, text, if_version=file.version))
|
|
197
|
+
return result
|
|
198
|
+
except ConflictError as error:
|
|
199
|
+
if error.kind == "version":
|
|
200
|
+
await asyncio.sleep(random.random() * 0.005 * (attempt + 1))
|
|
201
|
+
continue
|
|
202
|
+
raise
|
|
203
|
+
raise MemoryToolFailure(f"Error: {path} kept changing while it was edited; try again")
|
|
204
|
+
|
|
205
|
+
async def str_replace(self, raw_path: str, old_str: str, new_str: Optional[str]) -> str:
|
|
206
|
+
path = self._path(raw_path)
|
|
207
|
+
if not isinstance(old_str, str) or not old_str:
|
|
208
|
+
raise MemoryToolFailure("Error: old_str must not be empty")
|
|
209
|
+
replacement = new_str or ""
|
|
210
|
+
|
|
211
|
+
def change(text: str) -> tuple[str, str]:
|
|
212
|
+
positions: list[int] = []
|
|
213
|
+
at = text.find(old_str)
|
|
214
|
+
while at != -1:
|
|
215
|
+
positions.append(at)
|
|
216
|
+
at = text.find(old_str, at + 1)
|
|
217
|
+
if not positions:
|
|
218
|
+
raise MemoryToolFailure(
|
|
219
|
+
f"No replacement was performed, old_str `{old_str}` did not appear verbatim in {raw_path}."
|
|
220
|
+
)
|
|
221
|
+
if len(positions) > 1:
|
|
222
|
+
lines = ", ".join(str(text[:p].count("\n") + 1) for p in positions)
|
|
223
|
+
raise MemoryToolFailure(
|
|
224
|
+
f"No replacement was performed. Multiple occurrences of old_str `{old_str}` in lines: {lines}. "
|
|
225
|
+
"Please ensure it is unique"
|
|
226
|
+
)
|
|
227
|
+
at = positions[0]
|
|
228
|
+
updated = text[:at] + replacement + text[at + len(old_str) :]
|
|
229
|
+
changed_line = text[:at].count("\n")
|
|
230
|
+
all_lines = updated.split("\n")
|
|
231
|
+
start = max(0, changed_line - 2)
|
|
232
|
+
end = min(len(all_lines), changed_line + 3)
|
|
233
|
+
snippet = numbered(all_lines[start:end], start + 1)
|
|
234
|
+
return updated, (
|
|
235
|
+
"The memory file has been edited. Here is the snippet showing the change (with line numbers):\n"
|
|
236
|
+
+ snippet
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
return await self._edit(
|
|
240
|
+
path, f"Error: The path {raw_path} does not exist. Please provide a valid path.", change
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
async def insert(self, raw_path: str, insert_line: int, insert_text: str) -> str:
|
|
244
|
+
path = self._path(raw_path)
|
|
245
|
+
|
|
246
|
+
def change(text: str) -> tuple[str, str]:
|
|
247
|
+
lines = split_lines(text)
|
|
248
|
+
if not isinstance(insert_line, int) or insert_line < 0 or insert_line > len(lines):
|
|
249
|
+
raise MemoryToolFailure(
|
|
250
|
+
f"Error: Invalid `insert_line` parameter: {insert_line}. "
|
|
251
|
+
f"It should be within the range of lines of the file: [0, {len(lines)}]"
|
|
252
|
+
)
|
|
253
|
+
lines.insert(insert_line, insert_text.rstrip("\n"))
|
|
254
|
+
return "\n".join(lines) + "\n", f"The file {raw_path} has been edited."
|
|
255
|
+
|
|
256
|
+
return await self._edit(path, f"Error: The path {raw_path} does not exist", change)
|
|
257
|
+
|
|
258
|
+
# ---- delete / rename ----------------------------------------------------------------
|
|
259
|
+
|
|
260
|
+
async def delete(self, raw_path: str) -> str:
|
|
261
|
+
path = self._path(raw_path)
|
|
262
|
+
if path == ROOT:
|
|
263
|
+
raise MemoryToolFailure("Error: Cannot delete the /memories directory itself")
|
|
264
|
+
kind = await self._guard(self._kind(path))
|
|
265
|
+
if kind == "none":
|
|
266
|
+
raise MemoryToolFailure(f"Error: The path {raw_path} does not exist")
|
|
267
|
+
if kind == "file":
|
|
268
|
+
await self._guard(self.store.delete([path]))
|
|
269
|
+
else:
|
|
270
|
+
await self._guard(self.store.delete_prefix(path + "/"))
|
|
271
|
+
return f"Successfully deleted {raw_path}"
|
|
272
|
+
|
|
273
|
+
async def rename(self, raw_old: str, raw_new: str) -> str:
|
|
274
|
+
source = self._path(raw_old)
|
|
275
|
+
target = self._path(raw_new)
|
|
276
|
+
if source == ROOT:
|
|
277
|
+
raise MemoryToolFailure("Error: Cannot rename the /memories directory itself")
|
|
278
|
+
if target == ROOT or is_inside(target, source):
|
|
279
|
+
raise MemoryToolFailure(f"Error: Cannot move {raw_old} into itself or onto /memories")
|
|
280
|
+
kind = await self._guard(self._kind(source))
|
|
281
|
+
if kind == "none":
|
|
282
|
+
raise MemoryToolFailure(f"Error: The path {raw_old} does not exist")
|
|
283
|
+
if await self._guard(self._kind(target)) != "none":
|
|
284
|
+
raise MemoryToolFailure(f"Error: The destination {raw_new} already exists")
|
|
285
|
+
for ancestor in ancestors(target):
|
|
286
|
+
if await self._guard(self.store.get(ancestor)):
|
|
287
|
+
raise MemoryToolFailure(f"Error: {ancestor} is a file, so {raw_new} cannot be created inside it")
|
|
288
|
+
sources = [source] if kind == "file" else [e.path for e in await self._guard(self.store.list(source + "/"))]
|
|
289
|
+
created: list[str] = []
|
|
290
|
+
try:
|
|
291
|
+
for path in sources:
|
|
292
|
+
file = await self._guard(self.store.get(path))
|
|
293
|
+
if file is None:
|
|
294
|
+
raise MemoryToolFailure(f"Error: The path {path} does not exist")
|
|
295
|
+
destination = target if kind == "file" else target + path[len(source) :]
|
|
296
|
+
await self._guard(self.store.put(destination, file.text, create_only=True))
|
|
297
|
+
created.append(destination)
|
|
298
|
+
except ConflictError as error:
|
|
299
|
+
await self._undo(created)
|
|
300
|
+
raise MemoryToolFailure(f"Error: The destination {raw_new} already exists") from error
|
|
301
|
+
except BaseException:
|
|
302
|
+
# Copy first, delete second: a failure here leaves the original intact.
|
|
303
|
+
await self._undo(created)
|
|
304
|
+
raise
|
|
305
|
+
await self._guard(self.store.delete(sources))
|
|
306
|
+
return f"Successfully renamed {raw_old} to {raw_new}"
|
|
307
|
+
|
|
308
|
+
async def _undo(self, created: Sequence[str]) -> None:
|
|
309
|
+
try:
|
|
310
|
+
await self.store.delete(list(created))
|
|
311
|
+
except Exception: # noqa: BLE001 - best effort; the originals are untouched
|
|
312
|
+
pass
|
|
313
|
+
|
|
314
|
+
# ---- recall -------------------------------------------------------------------------
|
|
315
|
+
|
|
316
|
+
async def recall(self, query: str, k: int = 5) -> str:
|
|
317
|
+
if not isinstance(query, str) or not query.strip():
|
|
318
|
+
raise MemoryToolFailure("Error: query must be a non-empty string")
|
|
319
|
+
if not isinstance(k, int) or isinstance(k, bool) or not 1 <= k <= 50:
|
|
320
|
+
raise MemoryToolFailure("Error: k must be an integer from 1 to 50")
|
|
321
|
+
hits = await self._guard(self.store.recall(query, k))
|
|
322
|
+
if not hits:
|
|
323
|
+
return "No memory files match that query."
|
|
324
|
+
rows = []
|
|
325
|
+
for i, hit in enumerate(hits, 1):
|
|
326
|
+
snippet = hit.text if len(hit.text) <= 400 else hit.text[:400] + "..."
|
|
327
|
+
rows.append(f"{i}. {hit.path} (relevance {hit.score:.2f})\n{snippet}")
|
|
328
|
+
return "\n\n".join(rows)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# Copyright 2024-2026 WritersLogic Contributors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Path validation for the /memories virtual filesystem.
|
|
4
|
+
|
|
5
|
+
Paths are storage keys, never real filesystem paths, but every path is still validated so
|
|
6
|
+
nothing outside /memories is ever addressed.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from urllib.parse import unquote
|
|
13
|
+
|
|
14
|
+
ROOT = "/memories"
|
|
15
|
+
MAX_PATH_BYTES = 240
|
|
16
|
+
MAX_SEGMENT_BYTES = 128
|
|
17
|
+
MAX_DEPTH = 16
|
|
18
|
+
|
|
19
|
+
_ENCODED = re.compile(r"%(2e|2f|5c|00)", re.IGNORECASE)
|
|
20
|
+
_FORBIDDEN = re.compile(r"[\x00-\x1f\x7f\\]")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class MemoryPathError(ValueError):
|
|
24
|
+
"""A path outside /memories or otherwise unacceptable."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def normalize_path(path: object) -> str:
|
|
28
|
+
"""Return the canonical form of ``path``: ROOT, or ROOT/segment/..., no trailing slash."""
|
|
29
|
+
if not isinstance(path, str) or not path:
|
|
30
|
+
raise MemoryPathError("Path must be a non-empty string")
|
|
31
|
+
# Percent-encoded separators and dots are rejected outright so a path that a later layer
|
|
32
|
+
# decodes cannot turn into a traversal.
|
|
33
|
+
if _ENCODED.search(path):
|
|
34
|
+
raise MemoryPathError(f"Path {path} contains an encoded separator or dot")
|
|
35
|
+
for candidate in (path, unquote(path)):
|
|
36
|
+
if _FORBIDDEN.search(candidate):
|
|
37
|
+
raise MemoryPathError(f"Path {path} contains a control character or backslash")
|
|
38
|
+
if any(segment in ("..", ".") for segment in candidate.split("/")):
|
|
39
|
+
raise MemoryPathError(f"Path {path} would escape /memories directory")
|
|
40
|
+
if path != ROOT and not path.startswith(ROOT + "/"):
|
|
41
|
+
raise MemoryPathError(f"Path must start with /memories, got: {path}")
|
|
42
|
+
trimmed = path.rstrip("/") if len(path) > len(ROOT) else path
|
|
43
|
+
if trimmed == ROOT:
|
|
44
|
+
return ROOT
|
|
45
|
+
segments = trimmed[len(ROOT) + 1 :].split("/")
|
|
46
|
+
if len(segments) > MAX_DEPTH:
|
|
47
|
+
raise MemoryPathError(f"Path {path} is nested more than {MAX_DEPTH} levels")
|
|
48
|
+
for segment in segments:
|
|
49
|
+
if not segment:
|
|
50
|
+
raise MemoryPathError(f"Path {path} contains an empty segment")
|
|
51
|
+
if segment.startswith("."):
|
|
52
|
+
raise MemoryPathError(f"Path {path} contains a hidden segment; names must not start with a dot")
|
|
53
|
+
if len(segment.encode()) > MAX_SEGMENT_BYTES:
|
|
54
|
+
raise MemoryPathError(f"Path {path} has a segment longer than {MAX_SEGMENT_BYTES} bytes")
|
|
55
|
+
if len(trimmed.encode()) > MAX_PATH_BYTES:
|
|
56
|
+
raise MemoryPathError(f"Path {path} is longer than {MAX_PATH_BYTES} bytes")
|
|
57
|
+
return trimmed
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def ancestors(path: str) -> list[str]:
|
|
61
|
+
"""Every proper ancestor of ``path`` below ROOT, shallowest first."""
|
|
62
|
+
parts = path[len(ROOT) + 1 :].split("/")
|
|
63
|
+
return [f"{ROOT}/{'/'.join(parts[:i])}" for i in range(1, len(parts))]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def is_inside(path: str, directory: str) -> bool:
|
|
67
|
+
return path == directory or path.startswith(directory + "/")
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
# Copyright 2024-2026 WritersLogic Contributors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Storage behind the memory tool: files addressed by path, kept in WARM through
|
|
4
|
+
the warm-mcp server so every file is also searchable."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import os
|
|
10
|
+
from contextlib import AsyncExitStack
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any, Optional, Protocol, Sequence
|
|
13
|
+
|
|
14
|
+
from mcp import Client, StdioServerParameters
|
|
15
|
+
|
|
16
|
+
TAG = "memory-file"
|
|
17
|
+
_PAGE = 200
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class StoredFile:
|
|
22
|
+
path: str
|
|
23
|
+
text: str
|
|
24
|
+
version: str
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class FileEntry:
|
|
29
|
+
path: str
|
|
30
|
+
bytes: int
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class RecallHit:
|
|
35
|
+
path: str
|
|
36
|
+
score: float
|
|
37
|
+
text: str
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ConflictError(Exception):
|
|
41
|
+
"""A put precondition failed: kind is ``"exists"`` or ``"version"``."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, kind: str, message: str) -> None:
|
|
44
|
+
super().__init__(message)
|
|
45
|
+
self.kind = kind
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class WarmToolError(Exception):
|
|
49
|
+
def __init__(self, code: str, message: str, details: Optional[dict[str, Any]] = None) -> None:
|
|
50
|
+
super().__init__(f"{message} ({code})")
|
|
51
|
+
self.code = code
|
|
52
|
+
self.message = message
|
|
53
|
+
self.details = details
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class FileStore(Protocol):
|
|
57
|
+
max_file_bytes: int
|
|
58
|
+
|
|
59
|
+
async def get(self, path: str) -> Optional[StoredFile]:
|
|
60
|
+
"""The file at ``path``, or None."""
|
|
61
|
+
|
|
62
|
+
async def put(
|
|
63
|
+
self, path: str, text: str, *, create_only: bool = False, if_version: Optional[str] = None
|
|
64
|
+
) -> str:
|
|
65
|
+
"""Create (``create_only``) or replace (``if_version``) a file; returns its new version."""
|
|
66
|
+
|
|
67
|
+
async def list(self, prefix: str) -> list[FileEntry]:
|
|
68
|
+
"""Every file whose path starts with ``prefix``, in path order."""
|
|
69
|
+
|
|
70
|
+
async def delete(self, paths: Sequence[str]) -> int:
|
|
71
|
+
"""Delete the given files; returns how many existed."""
|
|
72
|
+
|
|
73
|
+
async def delete_prefix(self, prefix: str) -> int:
|
|
74
|
+
"""Delete every file under ``prefix``."""
|
|
75
|
+
|
|
76
|
+
async def recall(self, query: str, k: int) -> list[RecallHit]:
|
|
77
|
+
"""The files most relevant to ``query``, best first."""
|
|
78
|
+
|
|
79
|
+
async def close(self) -> None:
|
|
80
|
+
"""Release the connection."""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class McpFileStore:
|
|
84
|
+
"""`FileStore` over an warm-mcp server: stdio (spawns the binary) or streamable HTTP.
|
|
85
|
+
|
|
86
|
+
The connection lives in a task of its own, opened and closed there, so `close()` may be
|
|
87
|
+
called from any task (the MCP client's task groups must exit in the task that entered them).
|
|
88
|
+
Requires asyncio.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
def __init__(self, client: Client, namespace: Optional[str], max_file_bytes: int) -> None:
|
|
92
|
+
self._client = client
|
|
93
|
+
self._namespace = namespace
|
|
94
|
+
self.max_file_bytes = max_file_bytes
|
|
95
|
+
self._stop: Optional[asyncio.Event] = None
|
|
96
|
+
self._owner: Optional["asyncio.Task[None]"] = None
|
|
97
|
+
|
|
98
|
+
@classmethod
|
|
99
|
+
async def connect(
|
|
100
|
+
cls,
|
|
101
|
+
*,
|
|
102
|
+
command: str = "warm-mcp",
|
|
103
|
+
args: Sequence[str] = (),
|
|
104
|
+
env: Optional[dict[str, str]] = None,
|
|
105
|
+
url: Optional[str] = None,
|
|
106
|
+
token: Optional[str] = None,
|
|
107
|
+
namespace: Optional[str] = None,
|
|
108
|
+
max_file_bytes: Optional[int] = None,
|
|
109
|
+
request_timeout: float = 60.0,
|
|
110
|
+
) -> "McpFileStore":
|
|
111
|
+
"""Spawn ``command`` over stdio, or connect to ``url`` (an ``warm-mcp --transport http`` endpoint).
|
|
112
|
+
|
|
113
|
+
Every request, the handshake included, fails after ``request_timeout`` seconds, for example when the server
|
|
114
|
+
exits at startup because its store is held by another process.
|
|
115
|
+
"""
|
|
116
|
+
loop = asyncio.get_running_loop()
|
|
117
|
+
ready: "asyncio.Future[McpFileStore]" = loop.create_future()
|
|
118
|
+
stop = asyncio.Event()
|
|
119
|
+
|
|
120
|
+
async def owner() -> None:
|
|
121
|
+
stack = AsyncExitStack()
|
|
122
|
+
try:
|
|
123
|
+
store = await cls._open(stack, command, args, env, url, token, namespace, max_file_bytes, request_timeout)
|
|
124
|
+
except Exception as error: # handed to the caller below
|
|
125
|
+
try:
|
|
126
|
+
await stack.aclose()
|
|
127
|
+
except Exception: # the open failure is the useful one
|
|
128
|
+
pass
|
|
129
|
+
if not ready.done():
|
|
130
|
+
ready.set_exception(error)
|
|
131
|
+
return
|
|
132
|
+
ready.set_result(store)
|
|
133
|
+
await stop.wait()
|
|
134
|
+
await stack.aclose()
|
|
135
|
+
|
|
136
|
+
task = loop.create_task(owner())
|
|
137
|
+
try:
|
|
138
|
+
store = await ready
|
|
139
|
+
except (Exception, asyncio.CancelledError):
|
|
140
|
+
task.cancel()
|
|
141
|
+
raise
|
|
142
|
+
store._stop, store._owner = stop, task
|
|
143
|
+
return store
|
|
144
|
+
|
|
145
|
+
@classmethod
|
|
146
|
+
async def _open(
|
|
147
|
+
cls,
|
|
148
|
+
stack: AsyncExitStack,
|
|
149
|
+
command: str,
|
|
150
|
+
args: Sequence[str],
|
|
151
|
+
env: Optional[dict[str, str]],
|
|
152
|
+
url: Optional[str],
|
|
153
|
+
token: Optional[str],
|
|
154
|
+
namespace: Optional[str],
|
|
155
|
+
max_file_bytes: Optional[int],
|
|
156
|
+
timeout: float,
|
|
157
|
+
) -> "McpFileStore":
|
|
158
|
+
if url is not None:
|
|
159
|
+
token = token or os.environ.get("WARM_MCP_TOKEN")
|
|
160
|
+
if token:
|
|
161
|
+
import httpx2
|
|
162
|
+
from mcp.client.streamable_http import streamable_http_client
|
|
163
|
+
|
|
164
|
+
http = httpx2.AsyncClient(headers={"authorization": f"Bearer {token}"})
|
|
165
|
+
await stack.enter_async_context(http)
|
|
166
|
+
transport = streamable_http_client(url, http_client=http)
|
|
167
|
+
client = await stack.enter_async_context(Client(transport, read_timeout_seconds=timeout))
|
|
168
|
+
else:
|
|
169
|
+
client = await stack.enter_async_context(Client(url, read_timeout_seconds=timeout))
|
|
170
|
+
else:
|
|
171
|
+
merged = {**os.environ, **(env or {})}
|
|
172
|
+
params = StdioServerParameters(command=command, args=list(args), env=merged)
|
|
173
|
+
client = await stack.enter_async_context(Client(params, read_timeout_seconds=timeout))
|
|
174
|
+
store = cls(client, namespace, 2**53)
|
|
175
|
+
stats = await store._call("stats", {})
|
|
176
|
+
reported = int(stats["limits"]["max_text_bytes"])
|
|
177
|
+
store.max_file_bytes = min(max_file_bytes, reported) if max_file_bytes else reported
|
|
178
|
+
return store
|
|
179
|
+
|
|
180
|
+
async def _call(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
|
|
181
|
+
if self._namespace:
|
|
182
|
+
arguments = {**arguments, "namespace": self._namespace}
|
|
183
|
+
result = await self._client.call_tool(name, arguments)
|
|
184
|
+
structured = result.structured_content
|
|
185
|
+
if result.is_error:
|
|
186
|
+
error = (structured or {}).get("error", {})
|
|
187
|
+
raise WarmToolError(error.get("code", "unknown"), error.get("message", "tool call failed"), error.get("details"))
|
|
188
|
+
return structured or {}
|
|
189
|
+
|
|
190
|
+
async def get(self, path: str) -> Optional[StoredFile]:
|
|
191
|
+
try:
|
|
192
|
+
out = await self._call("get", {"id": path})
|
|
193
|
+
except WarmToolError as error:
|
|
194
|
+
if error.code == "not_found":
|
|
195
|
+
return None
|
|
196
|
+
raise
|
|
197
|
+
return StoredFile(path, out["memory"]["text"], out["memory"]["version"])
|
|
198
|
+
|
|
199
|
+
async def put(
|
|
200
|
+
self, path: str, text: str, *, create_only: bool = False, if_version: Optional[str] = None
|
|
201
|
+
) -> str:
|
|
202
|
+
arguments: dict[str, Any] = {"id": path, "text": text, "tags": [TAG], "allow_empty": True}
|
|
203
|
+
if create_only:
|
|
204
|
+
arguments["create_only"] = True
|
|
205
|
+
if if_version:
|
|
206
|
+
arguments["if_version"] = if_version
|
|
207
|
+
try:
|
|
208
|
+
out = await self._call("remember", arguments)
|
|
209
|
+
except WarmToolError as error:
|
|
210
|
+
if error.code == "already_exists":
|
|
211
|
+
raise ConflictError("exists", error.message) from error
|
|
212
|
+
if error.code == "version_conflict":
|
|
213
|
+
raise ConflictError("version", error.message) from error
|
|
214
|
+
raise
|
|
215
|
+
return out["version"]
|
|
216
|
+
|
|
217
|
+
async def list(self, prefix: str) -> list[FileEntry]:
|
|
218
|
+
entries: list[FileEntry] = []
|
|
219
|
+
cursor: Optional[str] = None
|
|
220
|
+
while True:
|
|
221
|
+
arguments: dict[str, Any] = {"prefix": prefix, "limit": _PAGE, "tag": TAG}
|
|
222
|
+
if cursor:
|
|
223
|
+
arguments["cursor"] = cursor
|
|
224
|
+
out = await self._call("list", arguments)
|
|
225
|
+
entries.extend(FileEntry(m["id"], m["bytes"]) for m in out["memories"])
|
|
226
|
+
cursor = out.get("next_cursor")
|
|
227
|
+
if not cursor:
|
|
228
|
+
return entries
|
|
229
|
+
|
|
230
|
+
async def delete(self, paths: Sequence[str]) -> int:
|
|
231
|
+
deleted = 0
|
|
232
|
+
for i in range(0, len(paths), 500):
|
|
233
|
+
out = await self._call("forget", {"ids": list(paths[i : i + 500])})
|
|
234
|
+
deleted += out["deleted"]
|
|
235
|
+
return deleted
|
|
236
|
+
|
|
237
|
+
async def delete_prefix(self, prefix: str) -> int:
|
|
238
|
+
return await self.delete([entry.path for entry in await self.list(prefix)])
|
|
239
|
+
|
|
240
|
+
async def recall(self, query: str, k: int) -> list[RecallHit]:
|
|
241
|
+
out = await self._call("recall", {"query": query, "k": k, "tags": [TAG]})
|
|
242
|
+
return [RecallHit(r["memory"]["id"], r["score"], r["memory"]["text"]) for r in out["results"]]
|
|
243
|
+
|
|
244
|
+
async def close(self) -> None:
|
|
245
|
+
if self._stop is not None and self._owner is not None:
|
|
246
|
+
self._stop.set()
|
|
247
|
+
await self._owner
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
# Copyright 2024-2026 WritersLogic Contributors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Anthropic SDK memory tools backed by WARM.
|
|
4
|
+
|
|
5
|
+
`WarmMemoryTool` (async) subclasses `BetaAsyncAbstractMemoryTool` and
|
|
6
|
+
`WarmMemoryToolSync` subclasses `BetaAbstractMemoryTool`, so either plugs into
|
|
7
|
+
`client.beta.messages.tool_runner(tools=[...])`.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import threading
|
|
14
|
+
from typing import Any, Coroutine, Optional, TypeVar
|
|
15
|
+
|
|
16
|
+
from anthropic.lib.tools import (
|
|
17
|
+
BetaAbstractMemoryTool,
|
|
18
|
+
BetaAsyncAbstractMemoryTool,
|
|
19
|
+
BetaAsyncFunctionTool,
|
|
20
|
+
BetaFunctionTool,
|
|
21
|
+
ToolError,
|
|
22
|
+
)
|
|
23
|
+
from anthropic.types.beta import (
|
|
24
|
+
BetaMemoryTool20250818CreateCommand,
|
|
25
|
+
BetaMemoryTool20250818DeleteCommand,
|
|
26
|
+
BetaMemoryTool20250818InsertCommand,
|
|
27
|
+
BetaMemoryTool20250818RenameCommand,
|
|
28
|
+
BetaMemoryTool20250818StrReplaceCommand,
|
|
29
|
+
BetaMemoryTool20250818ViewCommand,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
from .core import MemoryFs, MemoryToolFailure
|
|
33
|
+
from .store import FileStore, McpFileStore
|
|
34
|
+
|
|
35
|
+
T = TypeVar("T")
|
|
36
|
+
|
|
37
|
+
_RECALL_DESCRIPTION = (
|
|
38
|
+
"Search your memory files for the ones most relevant to a query. Returns file paths with a "
|
|
39
|
+
"relevance score and a text excerpt. Use `memory` view to read a file in full."
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def _failing(fs_call: Coroutine[Any, Any, str]) -> str:
|
|
44
|
+
try:
|
|
45
|
+
return await fs_call
|
|
46
|
+
except MemoryToolFailure as error:
|
|
47
|
+
raise ToolError(str(error)) from error
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class WarmMemoryTool(BetaAsyncAbstractMemoryTool):
|
|
51
|
+
"""Async memory tool over a `FileStore` (by default an warm-mcp server)."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, store: FileStore, *, max_view_chars: int = 16_000, edit_retries: int = 25, **kwargs: Any) -> None:
|
|
54
|
+
super().__init__(**kwargs)
|
|
55
|
+
self.fs = MemoryFs(store, max_view_chars=max_view_chars, edit_retries=edit_retries)
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
async def connect(cls, *, max_view_chars: int = 16_000, edit_retries: int = 25, **connection: Any) -> "WarmMemoryTool":
|
|
59
|
+
"""Connect to warm-mcp: ``command=``/``args=``/``env=`` for stdio, or ``url=``/``token=``."""
|
|
60
|
+
store = await McpFileStore.connect(**connection)
|
|
61
|
+
return cls(store, max_view_chars=max_view_chars, edit_retries=edit_retries)
|
|
62
|
+
|
|
63
|
+
async def aclose(self) -> None:
|
|
64
|
+
await self.fs.store.close()
|
|
65
|
+
|
|
66
|
+
async def __aenter__(self) -> "WarmMemoryTool":
|
|
67
|
+
return self
|
|
68
|
+
|
|
69
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
70
|
+
await self.aclose()
|
|
71
|
+
|
|
72
|
+
async def view(self, command: BetaMemoryTool20250818ViewCommand) -> str: # type: ignore[override]
|
|
73
|
+
return await _failing(self.fs.view(command.path, getattr(command, "view_range", None) or None))
|
|
74
|
+
|
|
75
|
+
async def create(self, command: BetaMemoryTool20250818CreateCommand) -> str: # type: ignore[override]
|
|
76
|
+
return await _failing(self.fs.create(command.path, command.file_text))
|
|
77
|
+
|
|
78
|
+
async def str_replace(self, command: BetaMemoryTool20250818StrReplaceCommand) -> str: # type: ignore[override]
|
|
79
|
+
return await _failing(self.fs.str_replace(command.path, command.old_str, getattr(command, "new_str", None)))
|
|
80
|
+
|
|
81
|
+
async def insert(self, command: BetaMemoryTool20250818InsertCommand) -> str: # type: ignore[override]
|
|
82
|
+
return await _failing(self.fs.insert(command.path, command.insert_line, command.insert_text))
|
|
83
|
+
|
|
84
|
+
async def delete(self, command: BetaMemoryTool20250818DeleteCommand) -> str: # type: ignore[override]
|
|
85
|
+
return await _failing(self.fs.delete(command.path))
|
|
86
|
+
|
|
87
|
+
async def rename(self, command: BetaMemoryTool20250818RenameCommand) -> str: # type: ignore[override]
|
|
88
|
+
return await _failing(self.fs.rename(command.old_path, command.new_path))
|
|
89
|
+
|
|
90
|
+
async def recall(self, query: str, k: int = 5) -> str:
|
|
91
|
+
"""Semantic recall over memory files: the files most relevant to ``query``, best first."""
|
|
92
|
+
return await self.fs.recall(query, k)
|
|
93
|
+
|
|
94
|
+
def recall_tool(self) -> BetaAsyncFunctionTool[Any]:
|
|
95
|
+
"""A companion tool that lets Claude search its memory files by meaning.
|
|
96
|
+
|
|
97
|
+
Add it next to this tool: ``tools=[memory, memory.recall_tool()]``.
|
|
98
|
+
"""
|
|
99
|
+
owner = self
|
|
100
|
+
|
|
101
|
+
async def memory_recall(query: str, k: int = 5) -> str:
|
|
102
|
+
try:
|
|
103
|
+
return await owner.recall(query, k)
|
|
104
|
+
except MemoryToolFailure as error:
|
|
105
|
+
raise ToolError(str(error)) from error
|
|
106
|
+
|
|
107
|
+
memory_recall.__doc__ = _RECALL_DESCRIPTION
|
|
108
|
+
from anthropic import beta_async_tool
|
|
109
|
+
|
|
110
|
+
return beta_async_tool(memory_recall)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class _LoopThread:
|
|
114
|
+
"""A private event loop on a daemon thread, so the sync tool can drive the async MCP client."""
|
|
115
|
+
|
|
116
|
+
def __init__(self) -> None:
|
|
117
|
+
self.loop = asyncio.new_event_loop()
|
|
118
|
+
self._thread = threading.Thread(target=self.loop.run_forever, name="warm-memory-tool", daemon=True)
|
|
119
|
+
self._thread.start()
|
|
120
|
+
|
|
121
|
+
def run(self, coroutine: Coroutine[Any, Any, T]) -> T:
|
|
122
|
+
return asyncio.run_coroutine_threadsafe(coroutine, self.loop).result()
|
|
123
|
+
|
|
124
|
+
def stop(self) -> None:
|
|
125
|
+
self.loop.call_soon_threadsafe(self.loop.stop)
|
|
126
|
+
self._thread.join(timeout=5)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class WarmMemoryToolSync(BetaAbstractMemoryTool):
|
|
130
|
+
"""Sync memory tool: the same commands, for `client.beta.messages.tool_runner`."""
|
|
131
|
+
|
|
132
|
+
def __init__(
|
|
133
|
+
self,
|
|
134
|
+
store: FileStore,
|
|
135
|
+
*,
|
|
136
|
+
max_view_chars: int = 16_000,
|
|
137
|
+
edit_retries: int = 25,
|
|
138
|
+
loop: Optional[_LoopThread] = None,
|
|
139
|
+
**kwargs: Any,
|
|
140
|
+
) -> None:
|
|
141
|
+
"""``store`` must be usable from the loop thread; pass ``loop`` only when ``store`` was created on it."""
|
|
142
|
+
super().__init__(**kwargs)
|
|
143
|
+
self._loop = loop or _LoopThread()
|
|
144
|
+
self.fs = MemoryFs(store, max_view_chars=max_view_chars, edit_retries=edit_retries)
|
|
145
|
+
|
|
146
|
+
@classmethod
|
|
147
|
+
def connect(cls, *, max_view_chars: int = 16_000, edit_retries: int = 25, **connection: Any) -> "WarmMemoryToolSync":
|
|
148
|
+
"""Connect to warm-mcp: ``command=``/``args=``/``env=`` for stdio, or ``url=``/``token=``."""
|
|
149
|
+
loop = _LoopThread()
|
|
150
|
+
try:
|
|
151
|
+
store = loop.run(McpFileStore.connect(**connection))
|
|
152
|
+
except BaseException:
|
|
153
|
+
loop.stop()
|
|
154
|
+
raise
|
|
155
|
+
return cls(store, max_view_chars=max_view_chars, edit_retries=edit_retries, loop=loop)
|
|
156
|
+
|
|
157
|
+
def close(self) -> None:
|
|
158
|
+
try:
|
|
159
|
+
self._loop.run(self.fs.store.close())
|
|
160
|
+
finally:
|
|
161
|
+
self._loop.stop()
|
|
162
|
+
|
|
163
|
+
def __enter__(self) -> "WarmMemoryToolSync":
|
|
164
|
+
return self
|
|
165
|
+
|
|
166
|
+
def __exit__(self, *exc: object) -> None:
|
|
167
|
+
self.close()
|
|
168
|
+
|
|
169
|
+
def _run(self, coroutine: Coroutine[Any, Any, str]) -> str:
|
|
170
|
+
return self._loop.run(_failing(coroutine))
|
|
171
|
+
|
|
172
|
+
def view(self, command: BetaMemoryTool20250818ViewCommand) -> str: # type: ignore[override]
|
|
173
|
+
return self._run(self.fs.view(command.path, getattr(command, "view_range", None) or None))
|
|
174
|
+
|
|
175
|
+
def create(self, command: BetaMemoryTool20250818CreateCommand) -> str: # type: ignore[override]
|
|
176
|
+
return self._run(self.fs.create(command.path, command.file_text))
|
|
177
|
+
|
|
178
|
+
def str_replace(self, command: BetaMemoryTool20250818StrReplaceCommand) -> str: # type: ignore[override]
|
|
179
|
+
return self._run(self.fs.str_replace(command.path, command.old_str, getattr(command, "new_str", None)))
|
|
180
|
+
|
|
181
|
+
def insert(self, command: BetaMemoryTool20250818InsertCommand) -> str: # type: ignore[override]
|
|
182
|
+
return self._run(self.fs.insert(command.path, command.insert_line, command.insert_text))
|
|
183
|
+
|
|
184
|
+
def delete(self, command: BetaMemoryTool20250818DeleteCommand) -> str: # type: ignore[override]
|
|
185
|
+
return self._run(self.fs.delete(command.path))
|
|
186
|
+
|
|
187
|
+
def rename(self, command: BetaMemoryTool20250818RenameCommand) -> str: # type: ignore[override]
|
|
188
|
+
return self._run(self.fs.rename(command.old_path, command.new_path))
|
|
189
|
+
|
|
190
|
+
def recall(self, query: str, k: int = 5) -> str:
|
|
191
|
+
return self._loop.run(self.fs.recall(query, k))
|
|
192
|
+
|
|
193
|
+
def recall_tool(self) -> BetaFunctionTool[Any]:
|
|
194
|
+
owner = self
|
|
195
|
+
|
|
196
|
+
def memory_recall(query: str, k: int = 5) -> str:
|
|
197
|
+
try:
|
|
198
|
+
return owner.recall(query, k)
|
|
199
|
+
except MemoryToolFailure as error:
|
|
200
|
+
raise ToolError(str(error)) from error
|
|
201
|
+
|
|
202
|
+
memory_recall.__doc__ = _RECALL_DESCRIPTION
|
|
203
|
+
from anthropic import beta_tool
|
|
204
|
+
|
|
205
|
+
return beta_tool(memory_recall)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
__all__ = ["WarmMemoryTool", "WarmMemoryToolSync", "MemoryToolFailure"]
|