gigaevo-client 0.3.0__py3-none-any.whl
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.
- gigaevo_client/__init__.py +166 -0
- gigaevo_client/_base.py +496 -0
- gigaevo_client/_compat.py +104 -0
- gigaevo_client/agent_skills.py +410 -0
- gigaevo_client/agents.py +248 -0
- gigaevo_client/cache.py +82 -0
- gigaevo_client/chains.py +517 -0
- gigaevo_client/client.py +1174 -0
- gigaevo_client/config.py +289 -0
- gigaevo_client/embeddings.py +314 -0
- gigaevo_client/exceptions.py +21 -0
- gigaevo_client/memory_cards.py +301 -0
- gigaevo_client/models.py +571 -0
- gigaevo_client/platform.py +446 -0
- gigaevo_client/platform_client.py +292 -0
- gigaevo_client/py.typed +0 -0
- gigaevo_client/search_types.py +13 -0
- gigaevo_client/suite.py +89 -0
- gigaevo_client/watcher.py +124 -0
- gigaevo_client-0.3.0.dist-info/METADATA +262 -0
- gigaevo_client-0.3.0.dist-info/RECORD +23 -0
- gigaevo_client-0.3.0.dist-info/WHEEL +4 -0
- gigaevo_client-0.3.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""GigaEvo Python client library.
|
|
2
|
+
|
|
3
|
+
The package was renamed from ``gigaevo_memory`` to ``gigaevo_client``
|
|
4
|
+
in 0.3.0. The old import path remains available as a thin shim that
|
|
5
|
+
emits a :class:`DeprecationWarning` once per process — see
|
|
6
|
+
``gigaevo_memory/__init__.py``."""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
__version__ = "0.3.0"
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"GigaEvoConfig",
|
|
14
|
+
"GigaEvoClient",
|
|
15
|
+
"MemoryClient",
|
|
16
|
+
"PlatformClient",
|
|
17
|
+
"AsyncPlatformClient",
|
|
18
|
+
"PlatformMemoryClient",
|
|
19
|
+
"GigaEvoSuite",
|
|
20
|
+
"SearchType",
|
|
21
|
+
"CachePolicy",
|
|
22
|
+
"EntityRef",
|
|
23
|
+
"EntityResponse",
|
|
24
|
+
"ChainRecord",
|
|
25
|
+
"BulkSaveResult",
|
|
26
|
+
"ProbeResult",
|
|
27
|
+
"VersionInfo",
|
|
28
|
+
"VersionDetail",
|
|
29
|
+
"DiffResponse",
|
|
30
|
+
"FacetsResponse",
|
|
31
|
+
"AgentSpec",
|
|
32
|
+
"AgentSkillSpec",
|
|
33
|
+
"CapabilityHit",
|
|
34
|
+
"CareChainMetadata",
|
|
35
|
+
"ContextFileRef",
|
|
36
|
+
"EvolutionMeta",
|
|
37
|
+
"LineageResponse",
|
|
38
|
+
"LineageVersion",
|
|
39
|
+
"DifferentialChannelView",
|
|
40
|
+
"VersionScore",
|
|
41
|
+
"DuplicateMember",
|
|
42
|
+
"DuplicatePair",
|
|
43
|
+
"DuplicatesResponse",
|
|
44
|
+
"MemoryCardExplanation",
|
|
45
|
+
"MemoryCardSpec",
|
|
46
|
+
"DatasetMemoryCardSpec",
|
|
47
|
+
"SearchHitData",
|
|
48
|
+
"ChainDict",
|
|
49
|
+
"StepDict",
|
|
50
|
+
"AgentDict",
|
|
51
|
+
"AgentSkillDict",
|
|
52
|
+
"MemoryCardDict",
|
|
53
|
+
"EmbeddingProvider",
|
|
54
|
+
"SentenceTransformersProvider",
|
|
55
|
+
"HuggingFaceProvider",
|
|
56
|
+
"OpenAIProvider",
|
|
57
|
+
"MemoryApiProvider",
|
|
58
|
+
"get_default_provider",
|
|
59
|
+
"set_default_provider",
|
|
60
|
+
"MemoryError",
|
|
61
|
+
"NotFoundError",
|
|
62
|
+
"ConflictError",
|
|
63
|
+
"ConnectionError",
|
|
64
|
+
"ValidationError",
|
|
65
|
+
"probe",
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def __getattr__(name: str):
|
|
70
|
+
if name == "GigaEvoConfig":
|
|
71
|
+
from .config import GigaEvoConfig
|
|
72
|
+
|
|
73
|
+
return GigaEvoConfig
|
|
74
|
+
if name in {"GigaEvoClient", "MemoryClient"}:
|
|
75
|
+
# Both names resolve to the same class. ``MemoryClient`` is the
|
|
76
|
+
# legacy alias preserved for callers that haven't migrated yet.
|
|
77
|
+
from .client import GigaEvoClient
|
|
78
|
+
|
|
79
|
+
return GigaEvoClient
|
|
80
|
+
if name == "PlatformMemoryClient":
|
|
81
|
+
from .platform_client import PlatformMemoryClient
|
|
82
|
+
|
|
83
|
+
return PlatformMemoryClient
|
|
84
|
+
if name == "PlatformClient":
|
|
85
|
+
from .platform import PlatformClient
|
|
86
|
+
|
|
87
|
+
return PlatformClient
|
|
88
|
+
if name == "AsyncPlatformClient":
|
|
89
|
+
from .platform import AsyncPlatformClient
|
|
90
|
+
|
|
91
|
+
return AsyncPlatformClient
|
|
92
|
+
if name == "probe":
|
|
93
|
+
from .client import probe
|
|
94
|
+
|
|
95
|
+
return probe
|
|
96
|
+
if name == "GigaEvoSuite":
|
|
97
|
+
from .suite import GigaEvoSuite
|
|
98
|
+
|
|
99
|
+
return GigaEvoSuite
|
|
100
|
+
if name == "SearchType":
|
|
101
|
+
from .search_types import SearchType
|
|
102
|
+
|
|
103
|
+
return SearchType
|
|
104
|
+
if name == "CachePolicy":
|
|
105
|
+
from .cache import CachePolicy
|
|
106
|
+
|
|
107
|
+
return CachePolicy
|
|
108
|
+
if name in {
|
|
109
|
+
"EmbeddingProvider",
|
|
110
|
+
"SentenceTransformersProvider",
|
|
111
|
+
"HuggingFaceProvider",
|
|
112
|
+
"OpenAIProvider",
|
|
113
|
+
"MemoryApiProvider",
|
|
114
|
+
"get_default_provider",
|
|
115
|
+
"set_default_provider",
|
|
116
|
+
}:
|
|
117
|
+
from . import embeddings as _embeddings
|
|
118
|
+
|
|
119
|
+
return getattr(_embeddings, name)
|
|
120
|
+
if name in {
|
|
121
|
+
"MemoryError",
|
|
122
|
+
"NotFoundError",
|
|
123
|
+
"ConflictError",
|
|
124
|
+
"ConnectionError",
|
|
125
|
+
"ValidationError",
|
|
126
|
+
}:
|
|
127
|
+
from . import exceptions as _exceptions
|
|
128
|
+
|
|
129
|
+
return getattr(_exceptions, name)
|
|
130
|
+
if name in {
|
|
131
|
+
"AgentDict",
|
|
132
|
+
"AgentSkillDict",
|
|
133
|
+
"AgentSkillSpec",
|
|
134
|
+
"AgentSpec",
|
|
135
|
+
"CapabilityHit",
|
|
136
|
+
"BulkSaveResult",
|
|
137
|
+
"CareChainMetadata",
|
|
138
|
+
"ChainRecord",
|
|
139
|
+
"ChainDict",
|
|
140
|
+
"ContextFileRef",
|
|
141
|
+
"DiffResponse",
|
|
142
|
+
"DifferentialChannelView",
|
|
143
|
+
"DuplicateMember",
|
|
144
|
+
"DuplicatePair",
|
|
145
|
+
"DuplicatesResponse",
|
|
146
|
+
"EvolutionMeta",
|
|
147
|
+
"EntityRef",
|
|
148
|
+
"LineageResponse",
|
|
149
|
+
"LineageVersion",
|
|
150
|
+
"VersionScore",
|
|
151
|
+
"EntityResponse",
|
|
152
|
+
"FacetsResponse",
|
|
153
|
+
"MemoryCardDict",
|
|
154
|
+
"DatasetMemoryCardSpec",
|
|
155
|
+
"MemoryCardExplanation",
|
|
156
|
+
"MemoryCardSpec",
|
|
157
|
+
"ProbeResult",
|
|
158
|
+
"SearchHitData",
|
|
159
|
+
"StepDict",
|
|
160
|
+
"VersionDetail",
|
|
161
|
+
"VersionInfo",
|
|
162
|
+
}:
|
|
163
|
+
from . import models as _models
|
|
164
|
+
|
|
165
|
+
return getattr(_models, name)
|
|
166
|
+
raise AttributeError(f"module 'gigaevo_client' has no attribute {name!r}")
|
gigaevo_client/_base.py
ADDED
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
"""Shared infrastructure base class for MemoryClient.
|
|
2
|
+
|
|
3
|
+
Provides common HTTP, caching, and entity operations used across all entity mixins.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
from .cache import CacheEntry, CachePolicy, CacheStore
|
|
15
|
+
from ._compat import to_jsonable
|
|
16
|
+
from .exceptions import ConflictError, NotFoundError, ValidationError
|
|
17
|
+
from .models import EntityRef, EntityResponse
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
_TYPE_PLURAL = {
|
|
21
|
+
"chain": "chains",
|
|
22
|
+
"step": "steps",
|
|
23
|
+
"agent": "agents",
|
|
24
|
+
"agent_skill": "agent-skills",
|
|
25
|
+
"memory_card": "memory-cards",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class BaseMemoryClient:
|
|
30
|
+
"""Base class providing shared HTTP and caching infrastructure.
|
|
31
|
+
|
|
32
|
+
This class contains the core functionality used by all entity-specific mixins:
|
|
33
|
+
- HTTP client configuration
|
|
34
|
+
- Caching logic
|
|
35
|
+
- Generic entity CRUD operations
|
|
36
|
+
- Response handling
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
base_url: str = "http://localhost:8000",
|
|
42
|
+
cache_policy: CachePolicy = CachePolicy.TTL,
|
|
43
|
+
cache_ttl: int = 300,
|
|
44
|
+
timeout: float = 30.0,
|
|
45
|
+
freshness_on_miss: bool = False,
|
|
46
|
+
sse_prefetch: bool = False,
|
|
47
|
+
api_key: str | None = None,
|
|
48
|
+
):
|
|
49
|
+
"""Initialize the base memory client.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
base_url: Base URL of the Memory API server
|
|
53
|
+
cache_policy: Caching strategy (TTL, FRESHNESS_CHECK, SSE_PUSH)
|
|
54
|
+
cache_ttl: Time-to-live for TTL cache in seconds
|
|
55
|
+
timeout: HTTP request timeout in seconds
|
|
56
|
+
freshness_on_miss: Whether to perform freshness check on cache miss
|
|
57
|
+
sse_prefetch: Whether to prefetch entities via SSE
|
|
58
|
+
api_key: Optional API key sent on every request as the
|
|
59
|
+
``X-API-Key`` header. Required by strict-mode
|
|
60
|
+
deployments; safe to omit in opt-in mode where the
|
|
61
|
+
server returns an anonymous context.
|
|
62
|
+
"""
|
|
63
|
+
self._base_url = base_url.rstrip("/")
|
|
64
|
+
self._api_key = api_key
|
|
65
|
+
headers = {"X-API-Key": api_key} if api_key else None
|
|
66
|
+
self._http = httpx.Client(
|
|
67
|
+
base_url=self._base_url, timeout=timeout, headers=headers
|
|
68
|
+
)
|
|
69
|
+
self.cache = CacheStore(policy=cache_policy, ttl=cache_ttl)
|
|
70
|
+
self._freshness_on_miss = freshness_on_miss
|
|
71
|
+
self._sse_prefetch = sse_prefetch
|
|
72
|
+
|
|
73
|
+
def _get_entity(
|
|
74
|
+
self,
|
|
75
|
+
entity_type: str,
|
|
76
|
+
entity_id: str,
|
|
77
|
+
channel: str = "latest",
|
|
78
|
+
cache_ttl: int | None = None,
|
|
79
|
+
force_refresh: bool = False,
|
|
80
|
+
) -> dict:
|
|
81
|
+
"""Fetch an entity with caching logic.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
entity_type: Type of entity (chain, step, agent, memory_card)
|
|
85
|
+
entity_id: Unique identifier for the entity
|
|
86
|
+
channel: Version channel to retrieve (latest, stable, custom)
|
|
87
|
+
cache_ttl: Override default cache TTL for this request
|
|
88
|
+
force_refresh: Bypass cache and fetch from server
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
Dictionary with 'content', 'version_id', and 'entity_id' keys
|
|
92
|
+
"""
|
|
93
|
+
# Check cache
|
|
94
|
+
if not force_refresh:
|
|
95
|
+
entry = self.cache.get(entity_type, entity_id, channel)
|
|
96
|
+
if entry is not None:
|
|
97
|
+
if self.cache.policy == CachePolicy.FRESHNESS_CHECK:
|
|
98
|
+
# Conditional GET
|
|
99
|
+
headers = {"If-None-Match": entry.content_hash}
|
|
100
|
+
plural = _TYPE_PLURAL.get(entity_type, entity_type + "s")
|
|
101
|
+
resp = self._http.get(
|
|
102
|
+
f"/v1/{plural}/{entity_id}",
|
|
103
|
+
params={"channel": channel},
|
|
104
|
+
headers=headers,
|
|
105
|
+
)
|
|
106
|
+
if resp.status_code == 304:
|
|
107
|
+
return {
|
|
108
|
+
"content": entry.raw_content,
|
|
109
|
+
"version_id": entry.version_id,
|
|
110
|
+
"entity_id": entity_id,
|
|
111
|
+
}
|
|
112
|
+
data = self._handle_response(resp)
|
|
113
|
+
self._cache_response(entity_type, entity_id, channel, data)
|
|
114
|
+
return data
|
|
115
|
+
else:
|
|
116
|
+
return {
|
|
117
|
+
"content": entry.raw_content,
|
|
118
|
+
"version_id": entry.version_id,
|
|
119
|
+
"entity_id": entity_id,
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
# Cache miss: fetch from server
|
|
123
|
+
plural = _TYPE_PLURAL.get(entity_type, entity_type + "s")
|
|
124
|
+
resp = self._http.get(f"/v1/{plural}/{entity_id}", params={"channel": channel})
|
|
125
|
+
data = self._handle_response(resp)
|
|
126
|
+
self._cache_response(entity_type, entity_id, channel, data)
|
|
127
|
+
return data
|
|
128
|
+
|
|
129
|
+
def _save_entity(
|
|
130
|
+
self,
|
|
131
|
+
entity_type: str,
|
|
132
|
+
content: dict,
|
|
133
|
+
name: str,
|
|
134
|
+
tags: list[str] | None = None,
|
|
135
|
+
when_to_use: str | None = None,
|
|
136
|
+
author: str | None = None,
|
|
137
|
+
namespace: str | None = None,
|
|
138
|
+
entity_id: str | None = None,
|
|
139
|
+
channel: str = "latest",
|
|
140
|
+
evolution_meta: dict | None = None,
|
|
141
|
+
) -> EntityRef:
|
|
142
|
+
"""Create or update an entity.
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
entity_type: Type of entity (chain, step, agent, memory_card)
|
|
146
|
+
content: Entity content as a dictionary
|
|
147
|
+
name: Human-readable name for the entity
|
|
148
|
+
tags: Optional list of tags for categorization
|
|
149
|
+
when_to_use: Optional description of when to use this entity
|
|
150
|
+
author: Optional author attribution
|
|
151
|
+
namespace: Optional logical memory namespace
|
|
152
|
+
entity_id: If provided, update existing entity; otherwise create new
|
|
153
|
+
channel: Version channel to update (latest, stable, custom)
|
|
154
|
+
evolution_meta: Optional evolutionary metadata for chains/steps
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
EntityRef with entity_id, version_id, and channel
|
|
158
|
+
"""
|
|
159
|
+
plural = _TYPE_PLURAL.get(entity_type, entity_type + "s")
|
|
160
|
+
body: dict[str, Any] = {
|
|
161
|
+
"meta": {
|
|
162
|
+
"name": name,
|
|
163
|
+
"tags": tags or [],
|
|
164
|
+
"when_to_use": when_to_use,
|
|
165
|
+
"namespace": namespace,
|
|
166
|
+
"author": author,
|
|
167
|
+
},
|
|
168
|
+
"channel": channel,
|
|
169
|
+
"content": content,
|
|
170
|
+
}
|
|
171
|
+
if evolution_meta:
|
|
172
|
+
body["evolution_meta"] = evolution_meta
|
|
173
|
+
|
|
174
|
+
body = to_jsonable(body)
|
|
175
|
+
|
|
176
|
+
if entity_id:
|
|
177
|
+
resp = self._http.put(f"/v1/{plural}/{entity_id}", json=body)
|
|
178
|
+
else:
|
|
179
|
+
resp = self._http.post(f"/v1/{plural}", json=body)
|
|
180
|
+
|
|
181
|
+
data = self._handle_response(resp)
|
|
182
|
+
return EntityRef(
|
|
183
|
+
entity_id=data["entity_id"],
|
|
184
|
+
entity_type=entity_type,
|
|
185
|
+
version_id=data.get("version_id"),
|
|
186
|
+
channel=channel,
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
def _list_entities(
|
|
190
|
+
self,
|
|
191
|
+
entity_type: str,
|
|
192
|
+
limit: int = 50,
|
|
193
|
+
offset: int = 0,
|
|
194
|
+
channel: str = "latest",
|
|
195
|
+
*,
|
|
196
|
+
sort_by: str | None = None,
|
|
197
|
+
sort_dir: str | None = None,
|
|
198
|
+
favourites_only: bool | None = None,
|
|
199
|
+
tags: list[str] | None = None,
|
|
200
|
+
q: str | None = None,
|
|
201
|
+
namespace: str | None = None,
|
|
202
|
+
extra_params: dict[str, Any] | None = None,
|
|
203
|
+
) -> list[EntityResponse]:
|
|
204
|
+
"""List entities with pagination + CARE library knobs.
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
entity_type: Type of entity to list
|
|
208
|
+
limit: Maximum number of results to return
|
|
209
|
+
offset: Pagination offset
|
|
210
|
+
channel: Version channel to retrieve (latest, stable, custom)
|
|
211
|
+
sort_by: One of ``created_at``, ``last_run_at``, ``run_count``,
|
|
212
|
+
``display_name``. Routers default to ``last_run_at`` so the
|
|
213
|
+
CARE library home view "feels right" out of the box.
|
|
214
|
+
sort_dir: ``asc`` or ``desc``.
|
|
215
|
+
favourites_only: Filter to ``favourite=TRUE`` rows.
|
|
216
|
+
tags: Filter to entities whose ``tags`` JSONB contains ALL
|
|
217
|
+
listed tokens. Sent as repeated ``tags`` query params.
|
|
218
|
+
q: Case-insensitive substring across display_name / name /
|
|
219
|
+
description.
|
|
220
|
+
namespace: Restrict to a single CARE namespace.
|
|
221
|
+
|
|
222
|
+
Returns:
|
|
223
|
+
List of EntityResponse objects.
|
|
224
|
+
"""
|
|
225
|
+
plural = _TYPE_PLURAL.get(entity_type, entity_type + "s")
|
|
226
|
+
params: dict[str, Any] = {"limit": limit, "offset": offset, "channel": channel}
|
|
227
|
+
if sort_by is not None:
|
|
228
|
+
params["sort_by"] = sort_by
|
|
229
|
+
if sort_dir is not None:
|
|
230
|
+
params["sort_dir"] = sort_dir
|
|
231
|
+
if favourites_only is not None:
|
|
232
|
+
params["favourites_only"] = favourites_only
|
|
233
|
+
if tags:
|
|
234
|
+
# httpx sends a list value as repeated `tags=…` query params,
|
|
235
|
+
# which matches FastAPI's `tags: list[str] | None = Query(None)`.
|
|
236
|
+
params["tags"] = list(tags)
|
|
237
|
+
if q is not None:
|
|
238
|
+
params["q"] = q
|
|
239
|
+
if namespace is not None:
|
|
240
|
+
params["namespace"] = namespace
|
|
241
|
+
# Per-entity-type extras (e.g. `requires_tool` /
|
|
242
|
+
# `excludes_tool` for agent_skills) — merge last so an
|
|
243
|
+
# explicit kwarg above isn't accidentally clobbered.
|
|
244
|
+
if extra_params:
|
|
245
|
+
for k, v in extra_params.items():
|
|
246
|
+
if v is None:
|
|
247
|
+
continue
|
|
248
|
+
if isinstance(v, (list, tuple)) and not v:
|
|
249
|
+
continue
|
|
250
|
+
params[k] = v
|
|
251
|
+
|
|
252
|
+
resp = self._http.get(f"/v1/{plural}", params=params)
|
|
253
|
+
data = self._handle_response(resp)
|
|
254
|
+
items, _, _ = self._parse_list_payload(data, resp)
|
|
255
|
+
return items
|
|
256
|
+
|
|
257
|
+
def _list_entities_paged(
|
|
258
|
+
self,
|
|
259
|
+
entity_type: str,
|
|
260
|
+
cursor: str | None = None,
|
|
261
|
+
limit: int = 50,
|
|
262
|
+
channel: str = "latest",
|
|
263
|
+
*,
|
|
264
|
+
sort_by: str | None = None,
|
|
265
|
+
sort_dir: str | None = None,
|
|
266
|
+
favourites_only: bool | None = None,
|
|
267
|
+
tags: list[str] | None = None,
|
|
268
|
+
q: str | None = None,
|
|
269
|
+
namespace: str | None = None,
|
|
270
|
+
extra_params: dict[str, Any] | None = None,
|
|
271
|
+
) -> tuple[list[EntityResponse], str | None, bool]:
|
|
272
|
+
"""Cursor-paginated list. Returns ``(items, next_cursor, has_more)``.
|
|
273
|
+
|
|
274
|
+
Wraps the same `/v1/{plural}` endpoint as `_list_entities` but
|
|
275
|
+
reads the `X-Next-Cursor` and `X-Has-More` response headers
|
|
276
|
+
to expose stable keyset pagination at the typed-mixin level.
|
|
277
|
+
|
|
278
|
+
``cursor=None`` requests the first page. Subsequent calls pass
|
|
279
|
+
the returned ``next_cursor`` to continue. ``has_more=False``
|
|
280
|
+
signals end-of-stream.
|
|
281
|
+
"""
|
|
282
|
+
plural = _TYPE_PLURAL.get(entity_type, entity_type + "s")
|
|
283
|
+
params: dict[str, Any] = {"limit": limit, "channel": channel}
|
|
284
|
+
if cursor is not None:
|
|
285
|
+
params["cursor"] = cursor
|
|
286
|
+
if sort_by is not None:
|
|
287
|
+
params["sort_by"] = sort_by
|
|
288
|
+
if sort_dir is not None:
|
|
289
|
+
params["sort_dir"] = sort_dir
|
|
290
|
+
if favourites_only is not None:
|
|
291
|
+
params["favourites_only"] = favourites_only
|
|
292
|
+
if tags:
|
|
293
|
+
params["tags"] = list(tags)
|
|
294
|
+
if q is not None:
|
|
295
|
+
params["q"] = q
|
|
296
|
+
if namespace is not None:
|
|
297
|
+
params["namespace"] = namespace
|
|
298
|
+
if extra_params:
|
|
299
|
+
for k, v in extra_params.items():
|
|
300
|
+
if v is None:
|
|
301
|
+
continue
|
|
302
|
+
if isinstance(v, (list, tuple)) and not v:
|
|
303
|
+
continue
|
|
304
|
+
params[k] = v
|
|
305
|
+
|
|
306
|
+
resp = self._http.get(f"/v1/{plural}", params=params)
|
|
307
|
+
data = self._handle_response(resp)
|
|
308
|
+
items, next_cursor, has_more = self._parse_list_payload(data, resp)
|
|
309
|
+
return items, next_cursor, has_more
|
|
310
|
+
|
|
311
|
+
@staticmethod
|
|
312
|
+
def _parse_list_payload(
|
|
313
|
+
data: Any,
|
|
314
|
+
resp: httpx.Response,
|
|
315
|
+
) -> tuple[list[EntityResponse], str | None, bool]:
|
|
316
|
+
"""Parse both legacy bare-list and current page-envelope responses."""
|
|
317
|
+
if isinstance(data, dict):
|
|
318
|
+
raw_items = data.get("items", [])
|
|
319
|
+
next_cursor = data.get("next_cursor")
|
|
320
|
+
has_more = bool(data.get("has_more", False))
|
|
321
|
+
has_body_next_cursor = "next_cursor" in data
|
|
322
|
+
has_body_has_more = "has_more" in data
|
|
323
|
+
else:
|
|
324
|
+
raw_items = data
|
|
325
|
+
next_cursor = None
|
|
326
|
+
has_more = False
|
|
327
|
+
has_body_next_cursor = False
|
|
328
|
+
has_body_has_more = False
|
|
329
|
+
if not isinstance(raw_items, list):
|
|
330
|
+
raw_items = []
|
|
331
|
+
if not has_body_next_cursor:
|
|
332
|
+
next_cursor = resp.headers.get("X-Next-Cursor")
|
|
333
|
+
header_has_more = resp.headers.get("X-Has-More")
|
|
334
|
+
if not has_body_has_more and header_has_more is not None:
|
|
335
|
+
has_more = header_has_more.lower() == "true"
|
|
336
|
+
return [EntityResponse.model_validate(e) for e in raw_items], next_cursor, has_more
|
|
337
|
+
|
|
338
|
+
# ------------------------------------------------------------------ #
|
|
339
|
+
# CARE library mutation helpers (P0 §1.4) #
|
|
340
|
+
# ------------------------------------------------------------------ #
|
|
341
|
+
|
|
342
|
+
def _mark_favourite(
|
|
343
|
+
self, entity_type: str, entity_id: str, value: bool = True
|
|
344
|
+
) -> EntityResponse:
|
|
345
|
+
"""POST /v1/{plural}/{id}/favourite — toggle the favourite flag."""
|
|
346
|
+
plural = _TYPE_PLURAL.get(entity_type, entity_type + "s")
|
|
347
|
+
resp = self._http.post(
|
|
348
|
+
f"/v1/{plural}/{entity_id}/favourite",
|
|
349
|
+
json={"favourite": bool(value)},
|
|
350
|
+
)
|
|
351
|
+
data = self._handle_response(resp)
|
|
352
|
+
return EntityResponse.model_validate(data)
|
|
353
|
+
|
|
354
|
+
def _record_run(
|
|
355
|
+
self,
|
|
356
|
+
entity_type: str,
|
|
357
|
+
entity_id: str,
|
|
358
|
+
run_id: str | None = None,
|
|
359
|
+
) -> EntityResponse:
|
|
360
|
+
"""POST /v1/{plural}/{id}/run-recorded — bump run_count + last_run_at."""
|
|
361
|
+
plural = _TYPE_PLURAL.get(entity_type, entity_type + "s")
|
|
362
|
+
body: dict[str, Any] = {}
|
|
363
|
+
if run_id is not None:
|
|
364
|
+
body["run_id"] = run_id
|
|
365
|
+
resp = self._http.post(
|
|
366
|
+
f"/v1/{plural}/{entity_id}/run-recorded",
|
|
367
|
+
json=body,
|
|
368
|
+
)
|
|
369
|
+
data = self._handle_response(resp)
|
|
370
|
+
return EntityResponse.model_validate(data)
|
|
371
|
+
|
|
372
|
+
def _update_metadata(
|
|
373
|
+
self,
|
|
374
|
+
entity_type: str,
|
|
375
|
+
entity_id: str,
|
|
376
|
+
*,
|
|
377
|
+
display_name: str | None = None,
|
|
378
|
+
description: str | None = None,
|
|
379
|
+
tags: list[str] | None = None,
|
|
380
|
+
favourite: bool | None = None,
|
|
381
|
+
) -> EntityResponse:
|
|
382
|
+
"""PATCH /v1/{plural}/{id} — partial update of CARE-mutable fields.
|
|
383
|
+
|
|
384
|
+
Each kwarg is sent only when explicitly provided. Use ``tags=[]``
|
|
385
|
+
to clear tags (distinct from omitting). Does NOT create a new
|
|
386
|
+
version.
|
|
387
|
+
"""
|
|
388
|
+
plural = _TYPE_PLURAL.get(entity_type, entity_type + "s")
|
|
389
|
+
body: dict[str, Any] = {}
|
|
390
|
+
if display_name is not None:
|
|
391
|
+
body["display_name"] = display_name
|
|
392
|
+
if description is not None:
|
|
393
|
+
body["description"] = description
|
|
394
|
+
if tags is not None:
|
|
395
|
+
body["tags"] = list(tags)
|
|
396
|
+
if favourite is not None:
|
|
397
|
+
body["favourite"] = bool(favourite)
|
|
398
|
+
resp = self._http.patch(f"/v1/{plural}/{entity_id}", json=body)
|
|
399
|
+
data = self._handle_response(resp)
|
|
400
|
+
return EntityResponse.model_validate(data)
|
|
401
|
+
|
|
402
|
+
def _delete_entity(self, entity_type: str, entity_id: str) -> bool:
|
|
403
|
+
"""Soft-delete an entity.
|
|
404
|
+
|
|
405
|
+
Args:
|
|
406
|
+
entity_type: Type of entity to delete
|
|
407
|
+
entity_id: Unique identifier for the entity
|
|
408
|
+
|
|
409
|
+
Returns:
|
|
410
|
+
True if deletion was successful
|
|
411
|
+
"""
|
|
412
|
+
plural = _TYPE_PLURAL.get(entity_type, entity_type + "s")
|
|
413
|
+
resp = self._http.delete(f"/v1/{plural}/{entity_id}")
|
|
414
|
+
# Handle 204 No Content or 200 OK
|
|
415
|
+
if resp.status_code == 204:
|
|
416
|
+
return True
|
|
417
|
+
self._handle_response(resp)
|
|
418
|
+
return True
|
|
419
|
+
|
|
420
|
+
def _cache_response(
|
|
421
|
+
self,
|
|
422
|
+
entity_type: str,
|
|
423
|
+
entity_id: str,
|
|
424
|
+
channel: str,
|
|
425
|
+
data: dict,
|
|
426
|
+
) -> None:
|
|
427
|
+
"""Cache a successful API response.
|
|
428
|
+
|
|
429
|
+
Args:
|
|
430
|
+
entity_type: Type of entity
|
|
431
|
+
entity_id: Unique identifier for the entity
|
|
432
|
+
channel: Version channel
|
|
433
|
+
data: Response data to cache
|
|
434
|
+
"""
|
|
435
|
+
content = data.get("content", {})
|
|
436
|
+
self.cache.put(
|
|
437
|
+
CacheEntry(
|
|
438
|
+
entity_type=entity_type,
|
|
439
|
+
entity_id=entity_id,
|
|
440
|
+
channel=channel,
|
|
441
|
+
version_id=data.get("version_id", ""),
|
|
442
|
+
content_hash=self._content_hash(content),
|
|
443
|
+
raw_content=content,
|
|
444
|
+
)
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
@staticmethod
|
|
448
|
+
def _content_hash(content: dict) -> str:
|
|
449
|
+
"""Compute SHA-256 hash of content for ETag/freshness checks.
|
|
450
|
+
|
|
451
|
+
Args:
|
|
452
|
+
content: Content dictionary to hash
|
|
453
|
+
|
|
454
|
+
Returns:
|
|
455
|
+
Hexadecimal SHA-256 hash string
|
|
456
|
+
"""
|
|
457
|
+
return hashlib.sha256(json.dumps(content, sort_keys=True).encode()).hexdigest()
|
|
458
|
+
|
|
459
|
+
def _handle_response(self, resp: httpx.Response) -> dict:
|
|
460
|
+
"""Handle HTTP response, raising appropriate exceptions on error.
|
|
461
|
+
|
|
462
|
+
Args:
|
|
463
|
+
resp: HTTP response object
|
|
464
|
+
|
|
465
|
+
Returns:
|
|
466
|
+
Response JSON as a dictionary
|
|
467
|
+
|
|
468
|
+
Raises:
|
|
469
|
+
NotFoundError: If entity not found (404)
|
|
470
|
+
ConflictError: On optimistic concurrency conflict (409/412)
|
|
471
|
+
ValidationError: On request validation failure (422)
|
|
472
|
+
httpx.HTTPStatusError: For other HTTP errors
|
|
473
|
+
"""
|
|
474
|
+
if resp.status_code == 404:
|
|
475
|
+
raise NotFoundError(f"Not found: {resp.url}")
|
|
476
|
+
if resp.status_code in (409, 412):
|
|
477
|
+
raise ConflictError(f"Conflict: {resp.text}")
|
|
478
|
+
if resp.status_code == 422:
|
|
479
|
+
raise ValidationError(f"Validation error: {resp.text}")
|
|
480
|
+
resp.raise_for_status()
|
|
481
|
+
return resp.json()
|
|
482
|
+
|
|
483
|
+
def close(self) -> None:
|
|
484
|
+
"""Close the underlying HTTP client.
|
|
485
|
+
|
|
486
|
+
Should be called when done using the client, or use as a context manager.
|
|
487
|
+
"""
|
|
488
|
+
self._http.close()
|
|
489
|
+
|
|
490
|
+
def __enter__(self) -> BaseMemoryClient:
|
|
491
|
+
"""Context manager entry."""
|
|
492
|
+
return self
|
|
493
|
+
|
|
494
|
+
def __exit__(self, *args: Any) -> None:
|
|
495
|
+
"""Context manager exit - ensures HTTP client is closed."""
|
|
496
|
+
self.close()
|