ampup-memory 0.2.1__tar.gz → 0.3.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: ampup-memory
3
- Version: 0.2.1
3
+ Version: 0.3.0
4
4
  Summary: A thin Python client for an AmpUp Memory server: team memory for coding agents
5
5
  Project-URL: Homepage, https://github.com/A79-ai/ampup-memory
6
6
  Project-URL: Source, https://github.com/A79-ai/ampup-memory/tree/main/sdk/python
@@ -67,12 +67,45 @@ from it.
67
67
  `AMPUP_MEMORY_CONTEXT`, then the current one, and renews an expiring sign-in with the saved refresh token, writing
68
68
  it back where the CLI reads it.
69
69
 
70
+ ## Serving many tenants (platforms)
71
+
72
+ A platform (an app that serves many customers of its own) uses one platform key for all of them. Each request names
73
+ the tenant, by the platform's own id for that customer, and, optionally, the user acting in it. Memory creates a
74
+ tenant the first time a request names it and enrolls a user the same way; each tenant's memory, and what it learns,
75
+ stays inside it.
76
+
77
+ ```python
78
+ platform = AmpUpMemory("https://memory.example.com", "msk_...") # the platform key, on your server only
79
+
80
+ # Per request: a copy for that tenant and user. Copies share the connections; close only `platform`.
81
+ mem = platform.for_tenant("acme", name="Acme Corp").for_user("u_42", email="pat@example.com", name="Pat Lee")
82
+ run = mem.session("Draft the renewal email", harness="renewal-writer")
83
+ mem.ingest([{"source": "crm:note:9", "body": "...", "occurred_at": micros(datetime.now(timezone.utc)), "acl": ["user:u_42"]}])
84
+
85
+ platform.tenants.ensure("acme", name="Acme Corp") # {tenant, org, created}
86
+ platform.tenants.list(limit=100) # the platform's tenants and their usage
87
+ platform.tenants.forget_user("acme", "u_42") # a user leaves
88
+ platform.tenants.delete("acme") # purge the tenant; {purging: true} until it is done
89
+ ```
90
+
91
+ Or pass `tenant=`, `tenant_name=`, `user=`, `user_email=` and `user_name=` to the constructor. Tenant and user ids
92
+ are the platform's own: 1 to 128 printable ASCII characters, case-sensitive. Email and name are stored on the user
93
+ and kept up to date, never their identity. Names and emails can be any text: the client sends them percent-encoded
94
+ (UTF-8). A tenant's name only labels it when it is created. Without a user, a request is the tenant's own: it can
95
+ ingest and read what the whole tenant shares, but sessions, advice, `remember` and `forget` need a user. ACLs on
96
+ what the platform writes name its users as `user:<user id>` and the whole tenant as `group:all`.
97
+
98
+ Name each of your agents' sessions with its own `harness`, never one ending in `:sdk`: advice isn't learned from
99
+ those.
100
+
70
101
  ## Methods
71
102
 
72
103
  | Method | Route | Returns |
73
104
  |---|---|---|
74
- | `AmpUpMemory(server, token, *, org, team, timeout)` | | `token` may be `None` for a local server |
105
+ | `AmpUpMemory(server, token, *, org, team, tenant, tenant_name, user, user_email, user_name, timeout)` | | `token` may be `None` for a local server |
75
106
  | `AmpUpMemory.from_profile(context=None)` | | a client for a CLI context |
107
+ | `for_tenant(tenant, *, name=None)` | | a copy for another tenant, as the tenant itself |
108
+ | `for_user(user, *, email=None, name=None)` | | a copy for another user of the same tenant |
76
109
  | `me()` | `GET /me` | who you are: user, groups, scope, memberships |
77
110
  | `ingest(episodes)` | `POST /ingest` | every episode id; sent in batches of 500; needs an ingest or admin key |
78
111
  | `remember(source, body, *, acl, document)` | `POST /remember` | `{episode_id, scope, readers}`, or `{queued, message}` |
@@ -85,6 +118,11 @@ it back where the CLI reads it.
85
118
  | `Session.end(outcome, reward, *, transcript, reason)` | `POST /sessions/end` | `{ended, served, session_id}` |
86
119
  | `advice(question)` | `POST /advice` | advice outside any session |
87
120
  | `reward(run_id, reward, reason=None)` | `POST /runs/reward` | the id; rewards an ended session (written within a minute of its end) or a run |
121
+ | `tenants.ensure(tenant, name=None)` | `PUT /tenants/{tenant}` | `{tenant, org, created}` |
122
+ | `tenants.get(tenant)` | `GET /tenants/{tenant}` | `{tenant, org, created_at, limits, usage}`; 404 if unknown |
123
+ | `tenants.list(after=None, limit=None)` | `GET /tenants` | a page of the platform's tenants with usage (up to 500) |
124
+ | `tenants.delete(tenant)` | `DELETE /tenants/{tenant}` | purges the tenant; `{purging: true}` while it runs |
125
+ | `tenants.forget_user(tenant, user)` | `POST /tenants/{tenant}/users/{user}/forget` | forgets the user and what they wrote |
88
126
  | `micros(datetime)` | | `occurred_at` in microseconds since the epoch |
89
127
 
90
128
  Every failure raises `AmpUpMemoryError` with `status`, `message` and, on a 429, `retry_after`. An error the
@@ -48,12 +48,45 @@ from it.
48
48
  `AMPUP_MEMORY_CONTEXT`, then the current one, and renews an expiring sign-in with the saved refresh token, writing
49
49
  it back where the CLI reads it.
50
50
 
51
+ ## Serving many tenants (platforms)
52
+
53
+ A platform (an app that serves many customers of its own) uses one platform key for all of them. Each request names
54
+ the tenant, by the platform's own id for that customer, and, optionally, the user acting in it. Memory creates a
55
+ tenant the first time a request names it and enrolls a user the same way; each tenant's memory, and what it learns,
56
+ stays inside it.
57
+
58
+ ```python
59
+ platform = AmpUpMemory("https://memory.example.com", "msk_...") # the platform key, on your server only
60
+
61
+ # Per request: a copy for that tenant and user. Copies share the connections; close only `platform`.
62
+ mem = platform.for_tenant("acme", name="Acme Corp").for_user("u_42", email="pat@example.com", name="Pat Lee")
63
+ run = mem.session("Draft the renewal email", harness="renewal-writer")
64
+ mem.ingest([{"source": "crm:note:9", "body": "...", "occurred_at": micros(datetime.now(timezone.utc)), "acl": ["user:u_42"]}])
65
+
66
+ platform.tenants.ensure("acme", name="Acme Corp") # {tenant, org, created}
67
+ platform.tenants.list(limit=100) # the platform's tenants and their usage
68
+ platform.tenants.forget_user("acme", "u_42") # a user leaves
69
+ platform.tenants.delete("acme") # purge the tenant; {purging: true} until it is done
70
+ ```
71
+
72
+ Or pass `tenant=`, `tenant_name=`, `user=`, `user_email=` and `user_name=` to the constructor. Tenant and user ids
73
+ are the platform's own: 1 to 128 printable ASCII characters, case-sensitive. Email and name are stored on the user
74
+ and kept up to date, never their identity. Names and emails can be any text: the client sends them percent-encoded
75
+ (UTF-8). A tenant's name only labels it when it is created. Without a user, a request is the tenant's own: it can
76
+ ingest and read what the whole tenant shares, but sessions, advice, `remember` and `forget` need a user. ACLs on
77
+ what the platform writes name its users as `user:<user id>` and the whole tenant as `group:all`.
78
+
79
+ Name each of your agents' sessions with its own `harness`, never one ending in `:sdk`: advice isn't learned from
80
+ those.
81
+
51
82
  ## Methods
52
83
 
53
84
  | Method | Route | Returns |
54
85
  |---|---|---|
55
- | `AmpUpMemory(server, token, *, org, team, timeout)` | | `token` may be `None` for a local server |
86
+ | `AmpUpMemory(server, token, *, org, team, tenant, tenant_name, user, user_email, user_name, timeout)` | | `token` may be `None` for a local server |
56
87
  | `AmpUpMemory.from_profile(context=None)` | | a client for a CLI context |
88
+ | `for_tenant(tenant, *, name=None)` | | a copy for another tenant, as the tenant itself |
89
+ | `for_user(user, *, email=None, name=None)` | | a copy for another user of the same tenant |
57
90
  | `me()` | `GET /me` | who you are: user, groups, scope, memberships |
58
91
  | `ingest(episodes)` | `POST /ingest` | every episode id; sent in batches of 500; needs an ingest or admin key |
59
92
  | `remember(source, body, *, acl, document)` | `POST /remember` | `{episode_id, scope, readers}`, or `{queued, message}` |
@@ -66,6 +99,11 @@ it back where the CLI reads it.
66
99
  | `Session.end(outcome, reward, *, transcript, reason)` | `POST /sessions/end` | `{ended, served, session_id}` |
67
100
  | `advice(question)` | `POST /advice` | advice outside any session |
68
101
  | `reward(run_id, reward, reason=None)` | `POST /runs/reward` | the id; rewards an ended session (written within a minute of its end) or a run |
102
+ | `tenants.ensure(tenant, name=None)` | `PUT /tenants/{tenant}` | `{tenant, org, created}` |
103
+ | `tenants.get(tenant)` | `GET /tenants/{tenant}` | `{tenant, org, created_at, limits, usage}`; 404 if unknown |
104
+ | `tenants.list(after=None, limit=None)` | `GET /tenants` | a page of the platform's tenants with usage (up to 500) |
105
+ | `tenants.delete(tenant)` | `DELETE /tenants/{tenant}` | purges the tenant; `{purging: true}` while it runs |
106
+ | `tenants.forget_user(tenant, user)` | `POST /tenants/{tenant}/users/{user}/forget` | forgets the user and what they wrote |
69
107
  | `micros(datetime)` | | `occurred_at` in microseconds since the epoch |
70
108
 
71
109
  Every failure raises `AmpUpMemoryError` with `status`, `message` and, on a 429, `retry_after`. An error the
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "ampup-memory"
3
- version = "0.2.1"
3
+ version = "0.3.0"
4
4
  description = "A thin Python client for an AmpUp Memory server: team memory for coding agents"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -1,6 +1,6 @@
1
1
  """A thin client for an AmpUp Memory server: remember and search what your team knows, and get advice that
2
2
  improves as sessions are rewarded."""
3
3
 
4
- from ampup_memory.client import Advice, AmpUpMemory, AmpUpMemoryError, Episode, Hit, Moment, Session, micros
4
+ from ampup_memory.client import Advice, AmpUpMemory, AmpUpMemoryError, Episode, Hit, Moment, Session, Tenants, micros
5
5
 
6
- __all__ = ["Advice", "AmpUpMemory", "AmpUpMemoryError", "Episode", "Hit", "Moment", "Session", "micros"]
6
+ __all__ = ["Advice", "AmpUpMemory", "AmpUpMemoryError", "Episode", "Hit", "Moment", "Session", "Tenants", "micros"]
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  from datetime import datetime, timedelta, timezone
6
6
  from typing import Any, Literal, TypedDict, cast
7
+ from urllib.parse import quote
7
8
 
8
9
  import httpx
9
10
 
@@ -77,19 +78,23 @@ class AmpUpMemory:
77
78
  *,
78
79
  org: str | None = None,
79
80
  team: str | None = None,
81
+ tenant: str | None = None,
82
+ tenant_name: str | None = None,
83
+ user: str | None = None,
84
+ user_email: str | None = None,
85
+ user_name: str | None = None,
80
86
  timeout: float = 60,
81
87
  ) -> None:
88
+ """A client for `server`. A platform key names a `tenant` (its own id for one of its customers) and,
89
+ optionally, the `user` acting in it; see `for_tenant` and `for_user`."""
82
90
  headers = {}
83
91
  if token:
84
92
  headers["authorization"] = f"Bearer {token}"
85
- # The wire names keep the engine's original prefix: headers are an interface, not what a person types.
86
- if org:
87
- headers["x-memstore-org"] = org
88
- if team:
89
- if not org:
90
- raise ValueError("team needs an org")
91
- headers["x-memstore-team"] = team
92
93
  self._http = httpx.Client(base_url=server.rstrip("/"), headers=headers, timeout=timeout)
94
+ self._owns_http = True
95
+ self._headers = _identity(org, team, tenant, tenant_name, user, user_email, user_name)
96
+ self._tenant, self._tenant_name = tenant, tenant_name
97
+ self.tenants = Tenants(self)
93
98
 
94
99
  @classmethod
95
100
  def from_profile(cls, context: str | None = None, *, timeout: float = 60) -> AmpUpMemory:
@@ -97,8 +102,32 @@ class AmpUpMemory:
97
102
  p = credentials.load_profile(context)
98
103
  return cls(p.server, p.token, org=p.org, team=p.team, timeout=timeout)
99
104
 
105
+ def for_tenant(self, tenant: str, *, name: str | None = None) -> AmpUpMemory:
106
+ """A copy of this client for another tenant, as the tenant itself (no user). `name` labels the tenant
107
+ when this request creates it. The copy shares this client's connections: close this one, not the copy."""
108
+ return self._copy(_identity(None, None, tenant, name, None, None, None), tenant, name)
109
+
110
+ def for_user(self, user: str, *, email: str | None = None, name: str | None = None) -> AmpUpMemory:
111
+ """A copy of this client for another user of the same tenant. `email` and `name` describe the user (they
112
+ are stored and kept up to date, never the user's identity). The copy shares this client's connections."""
113
+ if self._tenant is None:
114
+ raise ValueError("for_user needs a client with a tenant")
115
+ headers = _identity(None, None, self._tenant, self._tenant_name, user, email, name)
116
+ return self._copy(headers, self._tenant, self._tenant_name)
117
+
118
+ def _copy(self, headers: dict[str, str], tenant: str, tenant_name: str | None) -> AmpUpMemory:
119
+ c = object.__new__(AmpUpMemory)
120
+ c._http = self._http
121
+ c._owns_http = False
122
+ c._headers = headers
123
+ c._tenant, c._tenant_name = tenant, tenant_name
124
+ c.tenants = Tenants(c)
125
+ return c
126
+
100
127
  def close(self) -> None:
101
- self._http.close()
128
+ """Close the connections; a copy from `for_tenant` or `for_user` leaves them to the client it came from."""
129
+ if self._owns_http:
130
+ self._http.close()
102
131
 
103
132
  def __enter__(self) -> AmpUpMemory: # noqa: PYI034 (typing.Self needs 3.11)
104
133
  return self
@@ -106,8 +135,11 @@ class AmpUpMemory:
106
135
  def __exit__(self, *exc: object) -> None:
107
136
  self.close()
108
137
 
109
- def _call(self, method: str, path: str, body: Any = None) -> Any:
110
- r = self._http.request(method, path, json=body)
138
+ def _call(
139
+ self, method: str, path: str, body: Any = None, *, params: dict[str, Any] | None = None, scoped: bool = True
140
+ ) -> Any:
141
+ """One request. `scoped=False` leaves out the org, team, tenant and user headers."""
142
+ r = self._http.request(method, path, json=body, params=params, headers=self._headers if scoped else None)
111
143
  try:
112
144
  data = r.json()
113
145
  except ValueError:
@@ -170,7 +202,8 @@ class AmpUpMemory:
170
202
  """Start a session for `task`; its opening advice is `session.opening`.
171
203
 
172
204
  `harness` names what runs the session (your app, say). A name ending in ":sdk" marks the session a
173
- program's: advice isn't learned from it, nor served to it unless the org turns that on.
205
+ program's: advice isn't learned from it, nor served to it unless the org turns that on. A platform's agent
206
+ sessions use their own harness name, never one ending in ":sdk".
174
207
  """
175
208
  req: dict[str, Any] = {"context": task}
176
209
  if harness is not None:
@@ -193,6 +226,89 @@ class AmpUpMemory:
193
226
  return cast(str, self._call("POST", "/runs/reward", req)["run_id"])
194
227
 
195
228
 
229
+ def _identity(
230
+ org: str | None,
231
+ team: str | None,
232
+ tenant: str | None,
233
+ tenant_name: str | None,
234
+ user: str | None,
235
+ user_email: str | None,
236
+ user_name: str | None,
237
+ ) -> dict[str, str]:
238
+ """The headers that say which org or tenant, and which user, a request is for."""
239
+ if team and not org:
240
+ raise ValueError("team needs an org")
241
+ if tenant is not None and org:
242
+ raise ValueError("pass a tenant or an org, not both: a platform key reaches its tenants by their own ids")
243
+ if tenant is None and (tenant_name or user is not None):
244
+ raise ValueError("tenant_name and user need a tenant")
245
+ if user is None and (user_email or user_name):
246
+ raise ValueError("user_email and user_name need a user")
247
+ # The wire names keep the engine's original prefix: headers are an interface, not what a person types.
248
+ h: dict[str, str] = {}
249
+ if org:
250
+ h["x-memstore-org"] = org
251
+ if team:
252
+ h["x-memstore-team"] = team
253
+ # Ids go as they are, checked; the tenant's name and the user's email and name are attributes, sent as
254
+ # percent-encoded UTF-8 (RFC 3986, everything outside the unreserved set encoded) so any text travels.
255
+ for header, param, value, is_id in (
256
+ ("x-memstore-tenant", "tenant", tenant, True),
257
+ ("x-memstore-tenant-name", "tenant_name", tenant_name, False),
258
+ ("x-memstore-user", "user", user, True),
259
+ ("x-memstore-user-email", "user_email", user_email, False),
260
+ ("x-memstore-user-name", "user_name", user_name, False),
261
+ ):
262
+ if is_id and value is not None:
263
+ h[header] = _id(param, value)
264
+ elif value:
265
+ h[header] = quote(value, safe="")
266
+ return h
267
+
268
+
269
+ def _id(param: str, value: str) -> str:
270
+ """A tenant or user id: 1 to 128 printable ASCII characters."""
271
+ if not (1 <= len(value) <= 128 and all(" " <= c <= "~" for c in value)):
272
+ raise ValueError(f"{param} must be 1 to 128 printable ASCII characters: {value!r}")
273
+ return value
274
+
275
+
276
+ class Tenants:
277
+ """A platform key's tenants: `AmpUpMemory.tenants`. Each call names its tenant in the path, so it sends no
278
+ tenant or user headers, whatever the client was made for."""
279
+
280
+ def __init__(self, memory: AmpUpMemory) -> None:
281
+ self._memory = memory
282
+
283
+ def ensure(self, tenant: str, name: str | None = None) -> dict[str, Any]:
284
+ """Create the tenant if it doesn't exist: `{tenant, org, created}`. `name` labels it when it is created."""
285
+ body = {} if name is None else {"name": name}
286
+ return cast(dict[str, Any], self._memory._call("PUT", _tenant_path(tenant), body, scoped=False))
287
+
288
+ def get(self, tenant: str) -> dict[str, Any]:
289
+ """`{tenant, org, created_at, limits, usage}`; raises a 404 for a tenant that doesn't exist."""
290
+ return cast(dict[str, Any], self._memory._call("GET", _tenant_path(tenant), scoped=False))
291
+
292
+ def list(self, after: str | None = None, limit: int | None = None) -> dict[str, Any]:
293
+ """A page of the platform's tenants with their usage, after the tenant id `after` (up to 500 a page)."""
294
+ params = {k: v for k, v in (("after", after), ("limit", limit)) if v is not None}
295
+ return cast(dict[str, Any], self._memory._call("GET", "/tenants", params=params or None, scoped=False))
296
+
297
+ def delete(self, tenant: str) -> dict[str, Any]:
298
+ """Purge the tenant and everything in it. `{purging: true}` while the purge runs: call again to finish it.
299
+ The same id later starts a new, empty tenant."""
300
+ return cast(dict[str, Any], self._memory._call("DELETE", _tenant_path(tenant), scoped=False) or {})
301
+
302
+ def forget_user(self, tenant: str, user: str) -> dict[str, Any]:
303
+ """Forget one of the tenant's users: take them out of it and delete what they wrote there."""
304
+ path = f"{_tenant_path(tenant)}/users/{quote(_id('user', user), safe='')}/forget"
305
+ return cast(dict[str, Any], self._memory._call("POST", path, scoped=False) or {})
306
+
307
+
308
+ def _tenant_path(tenant: str) -> str:
309
+ return f"/tenants/{quote(_id('tenant', tenant), safe='')}"
310
+
311
+
196
312
  class Session:
197
313
  """One task's session: from `AmpUpMemory.session`."""
198
314
 
File without changes
File without changes
File without changes