ampup-memory 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.
@@ -0,0 +1,8 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ .mypy_cache/
5
+ .ruff_cache/
6
+ node_modules/
7
+ dist/
8
+ uv.lock
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,11 @@
1
+ AmpUp Memory
2
+ Copyright 2026 The AmpUp Memory Authors
3
+
4
+ This product includes software developed at
5
+ The Apache Software Foundation (https://www.apache.org/).
6
+
7
+ This product includes ONNX Runtime, Copyright (c) Microsoft Corporation, under the MIT License.
8
+
9
+ The memstore and memstore-client binaries include third-party software, each under its own license. Their license
10
+ texts, the NOTICE files of the Apache License 2.0 works among them, and ONNX Runtime's own third-party notices are
11
+ in THIRD-PARTY-NOTICES.txt, distributed with this product.
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.5
2
+ Name: ampup-memory
3
+ Version: 0.1.0
4
+ Summary: A thin Python client for an AmpUp Memory server: team memory for coding agents
5
+ Project-URL: Homepage, https://github.com/A79-ai/ampup-memory
6
+ Project-URL: Source, https://github.com/A79-ai/ampup-memory/tree/main/sdk/python
7
+ Project-URL: Issues, https://github.com/A79-ai/ampup-memory/issues
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Keywords: agents,ampup,llm,mcp,memory
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Typing :: Typed
16
+ Requires-Python: >=3.10
17
+ Requires-Dist: httpx>=0.27
18
+ Description-Content-Type: text/markdown
19
+
20
+ # ampup-memory
21
+
22
+ A thin Python client for an [AmpUp Memory](https://github.com/A79-ai/ampup-memory) server: write what your team
23
+ knows, search it, and read it back. One class, no codegen, and its only dependency is `httpx`.
24
+
25
+ ```sh
26
+ pip install ampup-memory
27
+ ```
28
+
29
+ ## Quickstart
30
+
31
+ ```python
32
+ from datetime import datetime, timezone
33
+ from ampup_memory import AmpUpMemory, micros
34
+
35
+ mem = AmpUpMemory.from_profile() # the CLI's current context; or AmpUpMemory.from_profile("work")
36
+ # mem = AmpUpMemory("https://memory.example.com", "msk_...", org="acme") # an explicit API key
37
+ # mem = AmpUpMemory("http://127.0.0.1:8080", None) # a local `ampup-memory serve --local`
38
+
39
+ ep = mem.remember("note:acme", "The Acme renewal is owned by Priya.")
40
+ print(mem.episode(ep["episode_id"]))
41
+ print(mem.search("who owns the Acme renewal", k=5))
42
+ print(mem.query({"find": "passages", "text": "Acme renewal"})["results"])
43
+ mem.ingest([{"source": "email:1", "body": "...", "occurred_at": micros(datetime.now(timezone.utc)), "acl": ["group:sales"]}])
44
+ ```
45
+
46
+ `from_profile()` uses the context and sign-in that `ampup-memory-client join <server> --org <org>` saved, in
47
+ `AMPUP_MEMORY_CONFIG_DIR` (default `~/.ampup-memory`). It picks the context from its argument, then
48
+ `AMPUP_MEMORY_CONTEXT`, then the current one, and renews an expiring sign-in with the saved refresh token, writing
49
+ it back where the CLI reads it.
50
+
51
+ ## Methods
52
+
53
+ | Method | Route | Returns |
54
+ |---|---|---|
55
+ | `AmpUpMemory(server, token, *, org, team, timeout)` | | `token` may be `None` for a local server |
56
+ | `AmpUpMemory.from_profile(context=None)` | | a client for a CLI context |
57
+ | `me()` | `GET /me` | who you are: user, groups, scope, memberships |
58
+ | `ingest(episodes)` | `POST /ingest` | every episode id; sent in batches of 500; needs an ingest or admin key |
59
+ | `remember(source, body, *, acl, document)` | `POST /remember` | `{episode_id, scope, readers}`, or `{queued, message}` |
60
+ | `forget(episode_id)` | `POST /forget` | the forgotten id |
61
+ | `search(query, k=10)` | `POST /search` | a list of fact hits |
62
+ | `query(q)` | `POST /query` | a query-language result (`find`: entities, facts, count, changes, passages, schema, metrics) |
63
+ | `episode(episode_id)` | `POST /episode` | the episode's text, or `None` |
64
+ | `micros(datetime)` | | `occurred_at` in microseconds since the epoch |
65
+
66
+ Every failure raises `AmpUpMemoryError` with `status`, `message` and, on a 429, `retry_after`. An error the
67
+ server reports inside a row (a bad query, say) raises it too, with status 200.
68
+
69
+ The TypeScript client with the same methods is [`@ampup/memory`](https://github.com/A79-ai/ampup-memory/tree/main/sdk/typescript).
70
+
71
+ ## License
72
+
73
+ Apache-2.0.
@@ -0,0 +1,54 @@
1
+ # ampup-memory
2
+
3
+ A thin Python client for an [AmpUp Memory](https://github.com/A79-ai/ampup-memory) server: write what your team
4
+ knows, search it, and read it back. One class, no codegen, and its only dependency is `httpx`.
5
+
6
+ ```sh
7
+ pip install ampup-memory
8
+ ```
9
+
10
+ ## Quickstart
11
+
12
+ ```python
13
+ from datetime import datetime, timezone
14
+ from ampup_memory import AmpUpMemory, micros
15
+
16
+ mem = AmpUpMemory.from_profile() # the CLI's current context; or AmpUpMemory.from_profile("work")
17
+ # mem = AmpUpMemory("https://memory.example.com", "msk_...", org="acme") # an explicit API key
18
+ # mem = AmpUpMemory("http://127.0.0.1:8080", None) # a local `ampup-memory serve --local`
19
+
20
+ ep = mem.remember("note:acme", "The Acme renewal is owned by Priya.")
21
+ print(mem.episode(ep["episode_id"]))
22
+ print(mem.search("who owns the Acme renewal", k=5))
23
+ print(mem.query({"find": "passages", "text": "Acme renewal"})["results"])
24
+ mem.ingest([{"source": "email:1", "body": "...", "occurred_at": micros(datetime.now(timezone.utc)), "acl": ["group:sales"]}])
25
+ ```
26
+
27
+ `from_profile()` uses the context and sign-in that `ampup-memory-client join <server> --org <org>` saved, in
28
+ `AMPUP_MEMORY_CONFIG_DIR` (default `~/.ampup-memory`). It picks the context from its argument, then
29
+ `AMPUP_MEMORY_CONTEXT`, then the current one, and renews an expiring sign-in with the saved refresh token, writing
30
+ it back where the CLI reads it.
31
+
32
+ ## Methods
33
+
34
+ | Method | Route | Returns |
35
+ |---|---|---|
36
+ | `AmpUpMemory(server, token, *, org, team, timeout)` | | `token` may be `None` for a local server |
37
+ | `AmpUpMemory.from_profile(context=None)` | | a client for a CLI context |
38
+ | `me()` | `GET /me` | who you are: user, groups, scope, memberships |
39
+ | `ingest(episodes)` | `POST /ingest` | every episode id; sent in batches of 500; needs an ingest or admin key |
40
+ | `remember(source, body, *, acl, document)` | `POST /remember` | `{episode_id, scope, readers}`, or `{queued, message}` |
41
+ | `forget(episode_id)` | `POST /forget` | the forgotten id |
42
+ | `search(query, k=10)` | `POST /search` | a list of fact hits |
43
+ | `query(q)` | `POST /query` | a query-language result (`find`: entities, facts, count, changes, passages, schema, metrics) |
44
+ | `episode(episode_id)` | `POST /episode` | the episode's text, or `None` |
45
+ | `micros(datetime)` | | `occurred_at` in microseconds since the epoch |
46
+
47
+ Every failure raises `AmpUpMemoryError` with `status`, `message` and, on a 429, `retry_after`. An error the
48
+ server reports inside a row (a bad query, say) raises it too, with status 200.
49
+
50
+ The TypeScript client with the same methods is [`@ampup/memory`](https://github.com/A79-ai/ampup-memory/tree/main/sdk/typescript).
51
+
52
+ ## License
53
+
54
+ Apache-2.0.
@@ -0,0 +1,34 @@
1
+ [project]
2
+ name = "ampup-memory"
3
+ version = "0.1.0"
4
+ description = "A thin Python client for an AmpUp Memory server: team memory for coding agents"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE", "NOTICE"]
8
+ requires-python = ">=3.10"
9
+ dependencies = ["httpx>=0.27"]
10
+ keywords = ["ampup", "memory", "agents", "llm", "mcp"]
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Intended Audience :: Developers",
14
+ "Programming Language :: Python :: 3",
15
+ "Typing :: Typed",
16
+ ]
17
+
18
+ [project.urls]
19
+ Homepage = "https://github.com/A79-ai/ampup-memory"
20
+ Source = "https://github.com/A79-ai/ampup-memory/tree/main/sdk/python"
21
+ Issues = "https://github.com/A79-ai/ampup-memory/issues"
22
+
23
+ [build-system]
24
+ requires = ["hatchling>=1.27"]
25
+ build-backend = "hatchling.build"
26
+
27
+ [tool.hatch.build.targets.wheel]
28
+ packages = ["src/ampup_memory"]
29
+
30
+ [tool.ruff]
31
+ line-length = 120
32
+
33
+ [tool.mypy]
34
+ strict = true
@@ -0,0 +1,5 @@
1
+ """A thin client for an AmpUp Memory server: remember, search and read what your team knows."""
2
+
3
+ from ampup_memory.client import AmpUpMemory, AmpUpMemoryError, Episode, Hit, micros
4
+
5
+ __all__ = ["AmpUpMemory", "AmpUpMemoryError", "Episode", "Hit", "micros"]
@@ -0,0 +1,149 @@
1
+ """A thin client for an AmpUp Memory server's HTTP API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timedelta, timezone
6
+ from typing import Any, TypedDict, cast
7
+
8
+ import httpx
9
+
10
+ from ampup_memory import credentials
11
+
12
+ INGEST_BATCH = 500
13
+
14
+
15
+ class _EpisodeRequired(TypedDict):
16
+ source: str
17
+ body: str
18
+ occurred_at: int # microseconds since the epoch, see micros()
19
+ acl: list[str] # at least one reader, never "*"
20
+
21
+
22
+ class Episode(_EpisodeRequired, total=False):
23
+ about: list[str]
24
+ index_text: bool
25
+ document: str
26
+
27
+
28
+ class Hit(TypedDict, total=False):
29
+ entity: str
30
+ predicate: str
31
+ value: Any
32
+ valid_from: str | None
33
+ valid_to: str | None
34
+ fact_id: str
35
+ source_episodes: list[str]
36
+ quote: str | None
37
+ score: float
38
+ written_by: str | None
39
+
40
+
41
+ class AmpUpMemoryError(Exception):
42
+ def __init__(self, status: int, message: str, retry_after: float | None = None) -> None:
43
+ super().__init__(f"HTTP {status}: {message}")
44
+ self.status = status
45
+ self.message = message
46
+ self.retry_after = retry_after
47
+
48
+
49
+ def micros(dt: datetime) -> int:
50
+ """`occurred_at` for an episode: microseconds since the epoch (naive datetimes are taken as local)."""
51
+ return (dt.astimezone() - _EPOCH) // timedelta(microseconds=1) # exact: no float on the way
52
+
53
+
54
+ _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
55
+
56
+
57
+ class AmpUpMemory:
58
+ def __init__(
59
+ self,
60
+ server: str,
61
+ token: str | None,
62
+ *,
63
+ org: str | None = None,
64
+ team: str | None = None,
65
+ timeout: float = 60,
66
+ ) -> None:
67
+ headers = {}
68
+ if token:
69
+ headers["authorization"] = f"Bearer {token}"
70
+ # The wire names keep the engine's original prefix: headers are an interface, not what a person types.
71
+ if org:
72
+ headers["x-memstore-org"] = org
73
+ if team:
74
+ if not org:
75
+ raise ValueError("team needs an org")
76
+ headers["x-memstore-team"] = team
77
+ self._http = httpx.Client(base_url=server.rstrip("/"), headers=headers, timeout=timeout)
78
+
79
+ @classmethod
80
+ def from_profile(cls, context: str | None = None, *, timeout: float = 60) -> AmpUpMemory:
81
+ """The server, org, team and sign-in that `ampup-memory-client join` saved for a context."""
82
+ p = credentials.load_profile(context)
83
+ return cls(p.server, p.token, org=p.org, team=p.team, timeout=timeout)
84
+
85
+ def close(self) -> None:
86
+ self._http.close()
87
+
88
+ def __enter__(self) -> AmpUpMemory: # noqa: PYI034 (typing.Self needs 3.11)
89
+ return self
90
+
91
+ def __exit__(self, *exc: object) -> None:
92
+ self.close()
93
+
94
+ def _call(self, method: str, path: str, body: Any = None) -> Any:
95
+ r = self._http.request(method, path, json=body)
96
+ try:
97
+ data = r.json()
98
+ except ValueError:
99
+ data = None
100
+ if r.is_error:
101
+ msg = data.get("error") if isinstance(data, dict) else None
102
+ retry = (data.get("retry_after_secs") if isinstance(data, dict) else None) or r.headers.get("retry-after")
103
+ raise AmpUpMemoryError(r.status_code, msg or r.text or r.reason_phrase, float(retry) if retry else None)
104
+ return data
105
+
106
+ def _row(self, path: str, *args: Any) -> Any:
107
+ """The row protocol: send one row `[0, *args]`, get back that row's value."""
108
+ out = self._call("POST", path, {"data": [[0, *args]]})["data"][0][1]
109
+ if isinstance(out, dict) and set(out) == {"error"}:
110
+ raise AmpUpMemoryError(200, out["error"])
111
+ return out
112
+
113
+ def me(self) -> dict[str, Any]:
114
+ """Who you are: user, groups, scope and memberships."""
115
+ return cast(dict[str, Any], self._call("GET", "/me"))
116
+
117
+ def ingest(self, episodes: list[Episode]) -> list[str]:
118
+ """Commit episodes in batches of 500; the ids of all of them. Needs an ingest or admin key."""
119
+ ids: list[str] = []
120
+ for i in range(0, len(episodes), INGEST_BATCH):
121
+ ids += self._call("POST", "/ingest", {"episodes": episodes[i : i + INGEST_BATCH]})["episode_ids"]
122
+ return ids
123
+
124
+ def remember(
125
+ self, source: str, body: str, *, acl: list[str] | None = None, document: str | None = None
126
+ ) -> dict[str, Any]:
127
+ """Add a note: `{episode_id, scope, readers}`, or `{queued, message}` when the server queues it."""
128
+ req: dict[str, Any] = {"source": source, "body": body}
129
+ if acl is not None:
130
+ req["acl"] = acl
131
+ if document is not None:
132
+ req["document"] = document
133
+ return cast(dict[str, Any], self._call("POST", "/remember", req))
134
+
135
+ def forget(self, episode_id: str) -> str:
136
+ """Forget an episode you wrote; its id."""
137
+ return cast(str, self._call("POST", "/forget", {"episode_id": episode_id})["forgotten"])
138
+
139
+ def search(self, query: str, k: int = 10) -> list[Hit]:
140
+ """The facts that best match `query`, with the episodes they came from."""
141
+ return cast(list[Hit], self._row("/search", query, k))
142
+
143
+ def query(self, q: dict[str, Any]) -> dict[str, Any]:
144
+ """A query-language request, e.g. {"find": "passages", "text": "renewal"}."""
145
+ return cast(dict[str, Any], self._row("/query", q))
146
+
147
+ def episode(self, episode_id: str) -> str | None:
148
+ """An episode's text, or None if it doesn't exist or you can't read it."""
149
+ return cast("str | None", self._row("/episode", episode_id))
@@ -0,0 +1,148 @@
1
+ """The context and sign-in that `ampup-memory-client join` saved, renewed when it expires.
2
+
3
+ They live where the CLI keeps them: `AMPUP_MEMORY_CONFIG_DIR` (or the older `MEMSTORE_CONFIG_DIR`), else
4
+ `~/.ampup-memory`, else `~/.memstore` on a machine where the CLI hasn't moved it yet.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import json
11
+ import os
12
+ import time
13
+ from collections.abc import Iterator
14
+ from contextlib import contextmanager
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import httpx
20
+
21
+ SIGN_IN = "`ampup-memory-client join <server> --org <org>`"
22
+
23
+
24
+ @dataclass
25
+ class Profile:
26
+ server: str
27
+ token: str
28
+ org: str | None = None
29
+ team: str | None = None
30
+
31
+
32
+ def _env(name: str) -> str | None:
33
+ """`AMPUP_MEMORY_<name>`, else the older `MEMSTORE_<name>` (the new name wins, as in the CLI)."""
34
+ return os.environ.get(f"AMPUP_MEMORY_{name}") or os.environ.get(f"MEMSTORE_{name}") or None
35
+
36
+
37
+ def config_dir() -> Path:
38
+ d = _env("CONFIG_DIR")
39
+ if d:
40
+ return Path(d)
41
+ new, old = Path.home() / ".ampup-memory", Path.home() / ".memstore"
42
+ if not os.path.lexists(new) and old.is_dir():
43
+ return old
44
+ return new
45
+
46
+
47
+ def _read(name: str) -> dict[str, Any]:
48
+ p = config_dir() / name
49
+ return json.loads(p.read_text()) if p.exists() else {}
50
+
51
+
52
+ def _write_private(name: str, data: dict[str, Any]) -> None:
53
+ d = config_dir()
54
+ d.mkdir(parents=True, exist_ok=True)
55
+ tmp = d / f".{name}.{os.getpid()}.tmp"
56
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
57
+ try:
58
+ with os.fdopen(fd, "w") as f:
59
+ f.write(json.dumps(data, indent=2))
60
+ f.flush()
61
+ os.fsync(f.fileno())
62
+ os.replace(tmp, d / name)
63
+ except BaseException:
64
+ tmp.unlink(missing_ok=True)
65
+ raise
66
+
67
+
68
+ @contextmanager
69
+ def _renewal_lock() -> Iterator[None]:
70
+ """The CLI's lock on `credentials.lock`, held while renewing: its hooks and MCP server renew the same sign-in,
71
+ and a refresh token used twice (where the provider rotates them) can sign the person out everywhere."""
72
+ d = config_dir()
73
+ d.mkdir(parents=True, exist_ok=True)
74
+ fd = os.open(d / "credentials.lock", os.O_WRONLY | os.O_CREAT, 0o600)
75
+ try:
76
+ try:
77
+ import fcntl
78
+ except ImportError: # Windows: no flock, renew unlocked
79
+ yield
80
+ return
81
+ fcntl.flock(fd, fcntl.LOCK_EX)
82
+ yield
83
+ finally:
84
+ os.close(fd)
85
+
86
+
87
+ def load_profile(context: str | None = None) -> Profile:
88
+ config = _read("config.json")
89
+ name = context or _env("CONTEXT") or config.get("current-context")
90
+ ctx = config.get("contexts", {}).get(name) if name else None
91
+ if not ctx or not ctx.get("server"):
92
+ raise RuntimeError(f"no context {name!r} with a server in {config_dir()}: run {SIGN_IN}")
93
+ server = ctx["server"].rstrip("/")
94
+ org = ctx.get("org")
95
+ all_creds = _read("credentials.json")
96
+ key = f"{server}#{org}" if org and f"{server}#{org}" in all_creds else server
97
+ if key not in all_creds:
98
+ raise RuntimeError(f"not signed in to {server}: run {SIGN_IN}")
99
+ return Profile(server, bearer(key), org, ctx.get("team"))
100
+
101
+
102
+ def bearer(key: str) -> str:
103
+ """The API key, else the ID (or access) token, renewed first if it expires within a minute."""
104
+ creds = _read("credentials.json")[key]
105
+ if creds.get("api_key"):
106
+ return str(creds["api_key"])
107
+ if creds.get("expires_at", 0) > time.time() + 60:
108
+ return _current(creds)
109
+ with _renewal_lock():
110
+ # Another process may have renewed while this one waited: take its sign-in, so its refresh token is newest.
111
+ all_creds = _read("credentials.json")
112
+ creds = all_creds[key]
113
+ if creds.get("expires_at", 0) <= time.time() + 60:
114
+ if not creds.get("refresh_token"):
115
+ raise RuntimeError(f"signed-in token expired: run {SIGN_IN}")
116
+ form = {
117
+ "grant_type": "refresh_token",
118
+ "refresh_token": creds["refresh_token"],
119
+ "client_id": creds.get("client_id", ""),
120
+ }
121
+ if creds.get("client_secret"):
122
+ form["client_secret"] = creds["client_secret"]
123
+ r = httpx.post(creds["token_endpoint"], data=form, headers={"accept": "application/json"}, timeout=30)
124
+ if r.is_error:
125
+ raise RuntimeError(f"renewing the sign-in failed ({r.status_code}): run {SIGN_IN}")
126
+ t = r.json()
127
+ creds["access_token"] = t["access_token"]
128
+ for k in ("id_token", "refresh_token"):
129
+ if t.get(k):
130
+ creds[k] = t[k]
131
+ creds["expires_at"] = _jwt_exp(creds.get("id_token")) or int(time.time()) + int(t.get("expires_in", 3600))
132
+ all_creds[key] = creds
133
+ _write_private("credentials.json", all_creds)
134
+ return _current(creds)
135
+
136
+
137
+ def _current(creds: dict[str, Any]) -> str:
138
+ return str(creds.get("id_token") or creds["access_token"])
139
+
140
+
141
+ def _jwt_exp(jwt: str | None) -> int | None:
142
+ if not jwt or jwt.count(".") != 2:
143
+ return None
144
+ payload = jwt.split(".")[1]
145
+ try:
146
+ return int(json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))["exp"])
147
+ except (ValueError, KeyError, TypeError):
148
+ return None
File without changes