prior-sdk 0.1.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.
Files changed (86) hide show
  1. console/__init__.py +5 -0
  2. console/client.py +81 -0
  3. prior/__init__.py +287 -0
  4. prior/__main__.py +8 -0
  5. prior/adapters/__init__.py +1 -0
  6. prior/adapters/custom.py +566 -0
  7. prior/adapters/horizons.py +114 -0
  8. prior/adapters/jupiter.py +266 -0
  9. prior/adapters/jupiter_predict.py +914 -0
  10. prior/adapters/prices/__init__.py +5 -0
  11. prior/adapters/prices/coingecko.py +203 -0
  12. prior/api/__init__.py +5 -0
  13. prior/api/__main__.py +24 -0
  14. prior/api/app.py +66 -0
  15. prior/api/routes/__init__.py +1 -0
  16. prior/api/routes/adapters.py +55 -0
  17. prior/api/routes/cases.py +192 -0
  18. prior/api/routes/checkbacks.py +25 -0
  19. prior/api/routes/common.py +331 -0
  20. prior/api/routes/evals.py +21 -0
  21. prior/api/routes/health.py +90 -0
  22. prior/api/routes/keys.py +54 -0
  23. prior/api/routes/memory.py +111 -0
  24. prior/api/routes/overview.py +219 -0
  25. prior/api/routes/recall.py +103 -0
  26. prior/api/routes/rules.py +309 -0
  27. prior/api/routes/subjects.py +89 -0
  28. prior/api/routes/usage.py +43 -0
  29. prior/checklist/__init__.py +58 -0
  30. prior/checklist/__main__.py +133 -0
  31. prior/checklist/decision.py +230 -0
  32. prior/checklist/filter.py +65 -0
  33. prior/checklist/label.py +43 -0
  34. prior/checklist/models.py +179 -0
  35. prior/checklist/retrieve.py +59 -0
  36. prior/checklist/skills.py +54 -0
  37. prior/checklist/store.py +231 -0
  38. prior/checklist/time.py +23 -0
  39. prior/cli/__init__.py +1 -0
  40. prior/cli/__main__.py +3 -0
  41. prior/cli/main.py +591 -0
  42. prior/core/__init__.py +34 -0
  43. prior/core/conditions.py +91 -0
  44. prior/core/errors.py +10 -0
  45. prior/core/models.py +394 -0
  46. prior/core/time.py +109 -0
  47. prior/mcp/__init__.py +27 -0
  48. prior/mcp/__main__.py +28 -0
  49. prior/mcp/http.py +185 -0
  50. prior/mcp/quota.py +37 -0
  51. prior/mcp/server.py +201 -0
  52. prior/mcp/tools.py +888 -0
  53. prior/recall.py +137 -0
  54. prior/replay.py +117 -0
  55. prior/sdk/__init__.py +39 -0
  56. prior/sdk/client.py +572 -0
  57. prior/sdk/errors.py +66 -0
  58. prior/sdk/facts.py +48 -0
  59. prior/sdk/http.py +140 -0
  60. prior/sdk/models.py +163 -0
  61. prior/sdk/ports.py +43 -0
  62. prior/sdk/queue.py +173 -0
  63. prior/sdk/spine.py +339 -0
  64. prior/sdk/time.py +79 -0
  65. prior/services/__init__.py +21 -0
  66. prior/services/benchmark.py +177 -0
  67. prior/services/bootstrap.py +61 -0
  68. prior/services/checkback.py +287 -0
  69. prior/services/consolidate.py +493 -0
  70. prior/services/evals.py +295 -0
  71. prior/services/gate_stats.py +717 -0
  72. prior/services/killswitch.py +81 -0
  73. prior/services/policy.py +79 -0
  74. prior/services/runner.py +319 -0
  75. prior/services/settle.py +178 -0
  76. prior/services/similar.py +97 -0
  77. prior/services/worker.py +248 -0
  78. prior/store/__init__.py +6 -0
  79. prior/store/ports.py +78 -0
  80. prior/store/sqlite.py +943 -0
  81. prior_sdk-0.1.0.dist-info/METADATA +523 -0
  82. prior_sdk-0.1.0.dist-info/RECORD +86 -0
  83. prior_sdk-0.1.0.dist-info/WHEEL +5 -0
  84. prior_sdk-0.1.0.dist-info/entry_points.txt +4 -0
  85. prior_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
  86. prior_sdk-0.1.0.dist-info/top_level.txt +2 -0
console/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Typed reader of Prior's public API. Not a visual console."""
2
+
3
+ from console.client import ApiError, ConsoleClient
4
+
5
+ __all__ = ["ApiError", "ConsoleClient"]
console/client.py ADDED
@@ -0,0 +1,81 @@
1
+ """Reads the public API. Every read sends as_of. This client does not filter time."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Mapping
7
+ from datetime import datetime
8
+ from typing import Any
9
+ from urllib import error, parse, request
10
+
11
+ from pydantic import TypeAdapter, ValidationError
12
+
13
+ from prior.core.models import ApiKey, Case, EvalSummary, MemoryItem, Page
14
+ from prior.core.time import format_utc
15
+
16
+ AsOf = datetime | str
17
+
18
+
19
+ class ApiError(Exception):
20
+ def __init__(self, *, type: str, message: str, field: str | None = None, status: int | None = None) -> None:
21
+ super().__init__(message)
22
+ self.type = type
23
+ self.message = message
24
+ self.field = field
25
+ self.status = status
26
+
27
+
28
+ class ConsoleClient:
29
+ def __init__(self, api_key: str, base_url: str, *, timeout: float = 10.0) -> None:
30
+ if not api_key or any(char.isspace() for char in api_key):
31
+ raise ValueError("api_key is required")
32
+ self._api_key = api_key
33
+ self.base_url = base_url.rstrip("/")
34
+ self._timeout = timeout
35
+
36
+ def list_cases(self, *, as_of: AsOf, filters: Mapping[str, str] | None = None) -> Page[Case]:
37
+ return self._read(Page[Case], "/cases", as_of, filters)
38
+
39
+ def get_case(self, case_id: str, *, as_of: AsOf) -> Case:
40
+ return self._read(Case, f"/cases/{parse.quote(case_id, safe='')}", as_of, None)
41
+
42
+ def list_memory(self, *, as_of: AsOf, filters: Mapping[str, str] | None = None) -> Page[MemoryItem]:
43
+ return self._read(Page[MemoryItem], "/memory", as_of, filters)
44
+
45
+ def eval_summary(self, *, as_of: AsOf) -> EvalSummary:
46
+ return self._read(EvalSummary, "/evals/latest", as_of, None)
47
+
48
+ def list_keys(self, *, as_of: AsOf) -> Page[ApiKey]:
49
+ return self._read(Page[ApiKey], "/keys", as_of, None)
50
+
51
+ def _read(self, model: Any, path: str, as_of: AsOf, params: Mapping[str, str] | None):
52
+ query = [("as_of", format_utc(as_of) if isinstance(as_of, datetime) else as_of)]
53
+ for key, value in (params or {}).items():
54
+ if key != "agent_id" and value is not None:
55
+ query.append((key, value))
56
+ url = f"{self.base_url}{path}?{parse.urlencode(query)}"
57
+ outgoing = request.Request(
58
+ url,
59
+ method="GET",
60
+ headers={"Authorization": f"Bearer {self._api_key}", "Accept": "application/json"},
61
+ )
62
+ try:
63
+ with request.urlopen(outgoing, timeout=self._timeout) as response:
64
+ status, body = response.status, response.read()
65
+ except error.HTTPError as exc:
66
+ status, body = exc.code, exc.read()
67
+ except error.URLError as exc:
68
+ raise ApiError(type="upstream_unavailable", message="the API could not be reached") from exc
69
+ payload = json.loads(body.decode()) if body else None
70
+ if status < 200 or status >= 300:
71
+ err = payload.get("error", {}) if isinstance(payload, dict) else {}
72
+ raise ApiError(
73
+ type=str(err.get("type") or "invalid_request"),
74
+ message=str(err.get("message") or "request failed"),
75
+ field=err.get("field"),
76
+ status=status,
77
+ )
78
+ try:
79
+ return TypeAdapter(model).validate_python(payload)
80
+ except ValidationError as exc:
81
+ raise ApiError(type="invalid_request", message="response did not match the public shape") from exc
prior/__init__.py ADDED
@@ -0,0 +1,287 @@
1
+ """One package. Recall advises. It does not decide.
2
+
3
+ `Prior.local(path)` returns the store facade: record a `Case`, append outcomes and
4
+ rule versions, recall against a cutoff, replay, and run the leak test. `Prior(store)`
5
+ returns the same facade for callers written before the split.
6
+ `Prior(api_key=...)` is the hosted client; `prior.sdk.Prior` is the client over a
7
+ local store port.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from datetime import datetime
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from prior.core.errors import PriorError
17
+ from prior.core.models import (
18
+ Case,
19
+ LookaheadAudit,
20
+ Outcome,
21
+ RecallResult,
22
+ Recalled,
23
+ RuleVersion,
24
+ Snapshot,
25
+ Subject,
26
+ )
27
+ from prior.core.time import VisibleAt, as_utc
28
+ from prior.recall import recall as recall_at
29
+ from prior.replay import replay as replay_case
30
+ from prior.sdk.client import Prior as _Client
31
+ from prior.sdk.errors import PriorValidationError
32
+ from prior.sdk.models import CasePage, CaseView, LeakTestReport, RecordedCase
33
+ from prior.sdk.spine import SpinePort, honesty_report
34
+ from prior.store import Store
35
+
36
+ __all__ = [
37
+ "Case",
38
+ "LookaheadAudit",
39
+ "Outcome",
40
+ "Prior",
41
+ "PriorError",
42
+ "PriorStore",
43
+ "RuleVersion",
44
+ "Snapshot",
45
+ "Subject",
46
+ ]
47
+
48
+
49
+ class _Borrowed:
50
+ """Hands the store to the client port without letting the client close it."""
51
+
52
+ def __init__(self, store: Store) -> None:
53
+ self._store = store
54
+
55
+ def record(self, case: Case) -> Case:
56
+ return self._store.record_case(case)
57
+
58
+ def recall(
59
+ self,
60
+ snapshot: Snapshot,
61
+ cutoff: datetime,
62
+ *,
63
+ agent_id: str,
64
+ subject_id: str | None = None,
65
+ ) -> RecallResult:
66
+ return recall_at(
67
+ self._store.visible_at(cutoff),
68
+ snapshot,
69
+ cutoff,
70
+ agent_id=agent_id,
71
+ subject_id=subject_id,
72
+ )
73
+
74
+ def cases(self, cutoff: datetime) -> tuple[Case, ...]:
75
+ return self._store.cases(cutoff)
76
+
77
+ def replay(self, case_id: str) -> LookaheadAudit:
78
+ return replay_case(self._store, case_id)
79
+
80
+ def __getattr__(self, name: str) -> Any:
81
+ return getattr(self._store, name)
82
+
83
+ def close(self) -> None:
84
+ return None
85
+
86
+
87
+ class _Cases:
88
+ """`cases(as_of)` is the visible slice; `cases.list` and `cases.show` read the spec API."""
89
+
90
+ def __init__(self, owner: PriorStore) -> None:
91
+ self._owner = owner
92
+
93
+ def __call__(self, as_of: datetime | str) -> tuple[Case, ...]:
94
+ return self._owner.visible_at(as_of).cases
95
+
96
+ def list(self, **query: Any) -> CasePage:
97
+ return self._owner._client().cases.list(**query)
98
+
99
+ def show(self, case_id: str, *, as_of: datetime | str | None = None) -> CaseView:
100
+ return self._owner._client().cases.show(case_id, as_of=as_of)
101
+
102
+
103
+ class PriorStore:
104
+ """The store facade. Answers store calls directly and the spec calls through the client."""
105
+
106
+ def __init__(
107
+ self,
108
+ store: Store,
109
+ *,
110
+ strict: bool = False,
111
+ timeout_ms: int = 300,
112
+ record_budget_ms: int = 50,
113
+ spill_path: str | Path | None = None,
114
+ retry_interval_s: float | None = 5.0,
115
+ agent_id: str | None = None,
116
+ ) -> None:
117
+ self._store = store
118
+ self._strict = strict
119
+ self._timeout_ms = timeout_ms
120
+ self._record_budget_ms = record_budget_ms
121
+ self._spill = Path(spill_path) if spill_path is not None else Path(".prior") / "spill.jsonl"
122
+ self._retry_interval_s = retry_interval_s
123
+ self._agent_id = agent_id
124
+ self._client_cache: _Client | None = None
125
+ self._closed = False
126
+ self._cases = _Cases(self)
127
+
128
+ @classmethod
129
+ def local(
130
+ cls,
131
+ path: str | Path,
132
+ *,
133
+ strict: bool = False,
134
+ timeout_ms: int = 300,
135
+ record_budget_ms: int = 50,
136
+ spill_path: str | Path | None = None,
137
+ retry_interval_s: float | None = 5.0,
138
+ agent_id: str | None = None,
139
+ ) -> PriorStore:
140
+ return cls(
141
+ Store(path),
142
+ strict=strict,
143
+ timeout_ms=timeout_ms,
144
+ record_budget_ms=record_budget_ms,
145
+ spill_path=spill_path if spill_path is not None else Path(str(path) + ".spill.jsonl"),
146
+ retry_interval_s=retry_interval_s,
147
+ agent_id=agent_id,
148
+ )
149
+
150
+ def _client(self) -> _Client:
151
+ if self._client_cache is None:
152
+ self._client_cache = _Client(
153
+ port=SpinePort(_Borrowed(self._store)),
154
+ strict=self._strict,
155
+ timeout_ms=self._timeout_ms,
156
+ record_budget_ms=self._record_budget_ms,
157
+ spill_path=self._spill,
158
+ retry_interval_s=self._retry_interval_s,
159
+ agent_id=self._agent_id,
160
+ require_agent=True,
161
+ )
162
+ return self._client_cache
163
+
164
+ @property
165
+ def cases(self) -> _Cases:
166
+ return self._cases
167
+
168
+ def record(self, case: Case | str, **fields: Any) -> Case | RecordedCase:
169
+ if isinstance(case, Case):
170
+ return self._record_case(case)
171
+ if isinstance(case, str):
172
+ return self._client().record(case, **fields)
173
+ raise PriorValidationError("record takes a Case or an action")
174
+
175
+ def _record_case(self, case: Case) -> Case:
176
+ if case.recalled is None:
177
+ visible = self._store.visible_at(case.decided_at)
178
+ result = recall_at(
179
+ visible,
180
+ case.snapshot,
181
+ visible.as_of,
182
+ agent_id=case.agent_id,
183
+ subject_id=case.subject_id,
184
+ )
185
+ case = case.model_copy(
186
+ update={
187
+ "recalled": Recalled(
188
+ trace_id=result.trace_id,
189
+ cutoff=visible.as_of,
190
+ retrieved=result.retrieved,
191
+ max_known_at=result.max_known_at,
192
+ )
193
+ }
194
+ )
195
+ return self._store.record_case(case)
196
+
197
+ def record_outcome(self, outcome: Outcome) -> Outcome:
198
+ return self._store.record_outcome(outcome)
199
+
200
+ def record_rule(self, version: RuleVersion) -> RuleVersion:
201
+ return self._store.record_rule(version)
202
+
203
+ def record_subject(self, subject: Subject) -> Subject:
204
+ return self._store.record_subject(subject)
205
+
206
+ def recall(
207
+ self,
208
+ snapshot: Snapshot | None = None,
209
+ cutoff: datetime | str | None = None,
210
+ *,
211
+ agent_id: str | None = None,
212
+ subject_id: str | None = None,
213
+ **fields: Any,
214
+ ) -> RecallResult | Any:
215
+ if isinstance(snapshot, Snapshot):
216
+ if cutoff is None:
217
+ raise PriorValidationError("as_of is required")
218
+ agent = agent_id or self._agent_id
219
+ if not agent:
220
+ raise PriorValidationError("agent_id is required")
221
+ visible = self._store.visible_at(cutoff)
222
+ return recall_at(visible, snapshot, visible.as_of, agent_id=agent, subject_id=subject_id)
223
+ if snapshot is not None or cutoff is not None:
224
+ raise PriorValidationError("recall takes a Snapshot and a cutoff, or the spec keyword arguments")
225
+ return self._client().recall(agent_id=agent_id or self._agent_id, **fields)
226
+
227
+ def replay(self, case_id: str) -> LookaheadAudit:
228
+ return replay_case(self._store, case_id)
229
+
230
+ def leak_test(self) -> LeakTestReport:
231
+ return honesty_report(self._store)
232
+
233
+ def visible_at(self, as_of: datetime | str) -> VisibleAt:
234
+ return self._store.visible_at(as_utc(as_of))
235
+
236
+ def outcomes(self, as_of: datetime | str) -> tuple[Outcome, ...]:
237
+ return self.visible_at(as_of).outcomes
238
+
239
+ def rule_versions(self, as_of: datetime | str) -> tuple[RuleVersion, ...]:
240
+ return self.visible_at(as_of).rule_versions
241
+
242
+ def subjects(self, as_of: datetime | str) -> tuple[Subject, ...]:
243
+ return self.visible_at(as_of).subjects
244
+
245
+ def close(self) -> None:
246
+ if self._closed:
247
+ return
248
+ self._closed = True
249
+ client, self._client_cache = self._client_cache, None
250
+ if client is not None:
251
+ client.close()
252
+ self._store.close()
253
+
254
+
255
+ class Prior(_Client):
256
+ """The client. A store passed first returns a PriorStore, and `Prior.local` opens one."""
257
+
258
+ def __new__(cls, *args: Any, **kwargs: Any) -> Any:
259
+ if cls is Prior and args:
260
+ first = args[0]
261
+ if isinstance(first, PriorStore):
262
+ return first
263
+ if hasattr(first, "record_case"):
264
+ return PriorStore(first)
265
+ return super().__new__(cls)
266
+
267
+ @classmethod
268
+ def local(
269
+ cls,
270
+ path: str | Path,
271
+ *,
272
+ strict: bool = False,
273
+ timeout_ms: int = 300,
274
+ record_budget_ms: int = 50,
275
+ spill_path: str | Path | None = None,
276
+ retry_interval_s: float | None = 5.0,
277
+ agent_id: str | None = None,
278
+ ) -> PriorStore:
279
+ return PriorStore.local(
280
+ path,
281
+ strict=strict,
282
+ timeout_ms=timeout_ms,
283
+ record_budget_ms=record_budget_ms,
284
+ spill_path=spill_path,
285
+ retry_interval_s=retry_interval_s,
286
+ agent_id=agent_id,
287
+ )
prior/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """`python -m prior` is the same entry point as `python -m prior.cli`."""
2
+
3
+ from prior.cli.main import main
4
+
5
+ __all__ = ["main"]
6
+
7
+ if __name__ == "__main__":
8
+ raise SystemExit(main())
@@ -0,0 +1 @@
1
+ """Venue and price adapters."""