brain-db-sdk 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.
Files changed (63) hide show
  1. brain_db_sdk-0.1.0/.gitignore +19 -0
  2. brain_db_sdk-0.1.0/LICENSE +201 -0
  3. brain_db_sdk-0.1.0/PKG-INFO +119 -0
  4. brain_db_sdk-0.1.0/README.md +95 -0
  5. brain_db_sdk-0.1.0/pyproject.toml +229 -0
  6. brain_db_sdk-0.1.0/src/brain_db_sdk/__init__.py +87 -0
  7. brain_db_sdk-0.1.0/src/brain_db_sdk/client.py +1101 -0
  8. brain_db_sdk-0.1.0/src/brain_db_sdk/errors.py +117 -0
  9. brain_db_sdk-0.1.0/src/brain_db_sdk/http/__init__.py +106 -0
  10. brain_db_sdk-0.1.0/src/brain_db_sdk/http/client.py +600 -0
  11. brain_db_sdk-0.1.0/src/brain_db_sdk/http/errors.py +25 -0
  12. brain_db_sdk-0.1.0/src/brain_db_sdk/http/retry.py +54 -0
  13. brain_db_sdk-0.1.0/src/brain_db_sdk/http/types.py +828 -0
  14. brain_db_sdk-0.1.0/src/brain_db_sdk/mux.py +401 -0
  15. brain_db_sdk-0.1.0/src/brain_db_sdk/pool.py +152 -0
  16. brain_db_sdk-0.1.0/src/brain_db_sdk/py.typed +0 -0
  17. brain_db_sdk-0.1.0/src/brain_db_sdk/retry.py +111 -0
  18. brain_db_sdk-0.1.0/src/brain_db_sdk/transport.py +57 -0
  19. brain_db_sdk-0.1.0/src/brain_db_sdk/verbs.py +263 -0
  20. brain_db_sdk-0.1.0/src/brain_db_sdk/wire/__init__.py +65 -0
  21. brain_db_sdk-0.1.0/src/brain_db_sdk/wire/cbor.py +300 -0
  22. brain_db_sdk-0.1.0/src/brain_db_sdk/wire/crc32c.py +42 -0
  23. brain_db_sdk-0.1.0/src/brain_db_sdk/wire/frame.py +191 -0
  24. brain_db_sdk-0.1.0/src/brain_db_sdk/wire/opcode.py +183 -0
  25. brain_db_sdk-0.1.0/src/brain_db_sdk/wire/types.py +7095 -0
  26. brain_db_sdk-0.1.0/tests/conftest.py +160 -0
  27. brain_db_sdk-0.1.0/tests/encode/test_encode.py +47 -0
  28. brain_db_sdk-0.1.0/tests/encode_vector/test_encode_vector.py +152 -0
  29. brain_db_sdk-0.1.0/tests/entity/test_entity.py +88 -0
  30. brain_db_sdk-0.1.0/tests/fixtures/recall_resp_10_results.hex +1 -0
  31. brain_db_sdk-0.1.0/tests/forget/test_forget.py +50 -0
  32. brain_db_sdk-0.1.0/tests/handshake/test_handshake.py +50 -0
  33. brain_db_sdk-0.1.0/tests/idempotency/test_idempotency.py +52 -0
  34. brain_db_sdk-0.1.0/tests/materialize/test_materialize.py +71 -0
  35. brain_db_sdk-0.1.0/tests/plan/test_plan.py +77 -0
  36. brain_db_sdk-0.1.0/tests/query/test_query.py +100 -0
  37. brain_db_sdk-0.1.0/tests/reason/test_reason.py +63 -0
  38. brain_db_sdk-0.1.0/tests/recall/test_recall.py +52 -0
  39. brain_db_sdk-0.1.0/tests/relation/test_relation.py +131 -0
  40. brain_db_sdk-0.1.0/tests/session/test_session.py +69 -0
  41. brain_db_sdk-0.1.0/tests/space/test_space.py +74 -0
  42. brain_db_sdk-0.1.0/tests/statement/test_statement.py +108 -0
  43. brain_db_sdk-0.1.0/tests/test_cbor_decoder.py +103 -0
  44. brain_db_sdk-0.1.0/tests/test_conformance.py +348 -0
  45. brain_db_sdk-0.1.0/tests/test_corpus_coverage.py +69 -0
  46. brain_db_sdk-0.1.0/tests/test_field_names.py +171 -0
  47. brain_db_sdk-0.1.0/tests/test_graph.py +263 -0
  48. brain_db_sdk-0.1.0/tests/test_handshake.py +263 -0
  49. brain_db_sdk-0.1.0/tests/test_http_client.py +758 -0
  50. brain_db_sdk-0.1.0/tests/test_http_edge.py +56 -0
  51. brain_db_sdk-0.1.0/tests/test_malformed.py +129 -0
  52. brain_db_sdk-0.1.0/tests/test_memory_list_and_trace.py +311 -0
  53. brain_db_sdk-0.1.0/tests/test_mux.py +568 -0
  54. brain_db_sdk-0.1.0/tests/test_pool.py +229 -0
  55. brain_db_sdk-0.1.0/tests/test_py_typed.py +85 -0
  56. brain_db_sdk-0.1.0/tests/test_read_side.py +708 -0
  57. brain_db_sdk-0.1.0/tests/test_relation_query_verbs.py +433 -0
  58. brain_db_sdk-0.1.0/tests/test_retry.py +265 -0
  59. brain_db_sdk-0.1.0/tests/test_schema_extractor_ping.py +297 -0
  60. brain_db_sdk-0.1.0/tests/test_space_id.py +16 -0
  61. brain_db_sdk-0.1.0/tests/test_stream_control.py +187 -0
  62. brain_db_sdk-0.1.0/tests/test_verbs.py +202 -0
  63. brain_db_sdk-0.1.0/uv.lock +370 -0
@@ -0,0 +1,19 @@
1
+ # Rust
2
+ /rust/target/
3
+ **/*.rs.bk
4
+
5
+ # Python
6
+ __pycache__/
7
+ *.py[cod]
8
+ .venv/
9
+ *.egg-info/
10
+ dist/
11
+ build/
12
+
13
+ # TypeScript / Node
14
+ node_modules/
15
+ /typescript/dist/
16
+ *.tsbuildinfo
17
+
18
+ # OS
19
+ .DS_Store
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Niraj Georgian
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,119 @@
1
+ Metadata-Version: 2.5
2
+ Name: brain-db-sdk
3
+ Version: 0.1.0
4
+ Summary: Python client SDK for the Brain memory database. Speaks Brain's BRN0 wire protocol directly over TCP.
5
+ Project-URL: Homepage, https://github.com/arc-labs-ai/brain-sdk
6
+ Project-URL: Repository, https://github.com/arc-labs-ai/brain-sdk
7
+ Author: Niraj Georgian
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: ai-agents,brain,client,database,memory
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Database
16
+ Classifier: Topic :: Software Development :: Libraries
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: cbor2>=5.9
19
+ Provides-Extra: dev
20
+ Requires-Dist: pyright>=1.1.400; extra == 'dev'
21
+ Requires-Dist: pytest>=8; extra == 'dev'
22
+ Requires-Dist: ruff>=0.16; extra == 'dev'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # brain-db-sdk (Python)
26
+
27
+ The Python client for the Brain memory database. Speaks Brain's BRN0 wire
28
+ protocol directly; no dependency on Brain's internal code.
29
+
30
+ **Status: typed-graph verbs (Phase 6).** The wire codec (Phase 1) is **verified
31
+ byte-for-byte against the shared conformance corpus** (all 86 `.bin`/`.json`
32
+ cases re-encode to identical bytes). On top of it, a synchronous connection
33
+ layer (a `transport` over a socket, a `Connection` running the handshake HELLO →
34
+ WELCOME → AUTH → AUTH_OK and request/response, a `BrainClient` holding the
35
+ negotiated session), the three v1 verbs with ergonomic builders (`encode()`,
36
+ `recall()` streaming to EOS / `recall_frames()`, `forget()`), a `with_retry`
37
+ helper + `RetryPolicy` (exponential backoff, server `retry_after_ms`), and the
38
+ typed-graph verbs: `create_entity()`, `create_statement()`, `create_relation()`,
39
+ `upload_schema()`, and `materialize_procedural()`; and the space/session registry
40
+ verbs: `create_space()` / `list_spaces()` / `delete_space()` and
41
+ `create_session()` / `list_sessions()` / `delete_session()` for managing the
42
+ per-request isolation unit (space) and conversation groupings (session) that a
43
+ trusted principal targets via `act_as`. `BrainClient` is built on a
44
+ `MuxConnection`: a background reader thread demultiplexes responses by
45
+ `stream_id`, so **every verb is concurrency-safe** and many requests run in
46
+ flight at once over one connection from multiple threads. A `Pool` opens a fixed
47
+ set of such connections and hands them out round-robin for socket-level
48
+ parallelism. Transparent reconnect and an `asyncio` client are later phases.
49
+
50
+ The full build plan is in the repo-root [`../PLAN.md`](../PLAN.md); the
51
+ layered architecture is in [`../ARCHITECTURE.md`](../ARCHITECTURE.md).
52
+
53
+ ```python
54
+ from brain_db_sdk import (
55
+ BrainClient, EncodeBuilder, RecallBuilder, ForgetBuilder, RetryPolicy, with_retry,
56
+ )
57
+
58
+ with BrainClient.connect("127.0.0.1", 7878) as client:
59
+ stored = client.encode(EncodeBuilder("the user prefers dark mode").build())
60
+ answer = client.recall(RecallBuilder("ui preferences").limit(5).build())
61
+ # answer.answer_kind is Single/Set (fact answer.values) or Episodic
62
+ # (memory answer.results); NoSubject/NoMemory means "don't know".
63
+ # Ride out transient ResourceExhausted/Unavailable; the stable request_id
64
+ # makes the resend idempotent.
65
+ req = ForgetBuilder(stored.memory_id).build()
66
+ with_retry(lambda: client.forget(req), RetryPolicy())
67
+ ```
68
+
69
+ Develop + verify against the corpus:
70
+
71
+ ```bash
72
+ python3 -m venv .venv && .venv/bin/pip install cbor2 pytest
73
+ PYTHONPATH=src .venv/bin/python -m pytest tests/ -q
74
+ ```
75
+
76
+ The integration suites run against a real server when `BRAIN_SDK_IT_DATA` is
77
+ set, and skip otherwise; `scripts/it-server.sh up` boots one and prints the
78
+ vars. Set `BRAIN_SDK_IT_REQUIRED=1` wherever a server is meant to be reachable
79
+ so a misconfigured one fails instead of reading as green.
80
+
81
+ Layout (folder-per-concern, mirroring the reference Rust SDK):
82
+
83
+ ```
84
+ src/brain_db_sdk/
85
+ wire/ frame + CBOR codec, opcodes, typed payloads (corpus-verified)
86
+ errors.py client error taxonomy (BrainError + subclasses)
87
+ transport.py sync read/write of whole frames over a socket
88
+ connection.py handshake + one-at-a-time request/response
89
+ client.py high-level BrainClient: connect, handshake, encode/recall/forget
90
+ verbs.py ergonomic EncodeBuilder / RecallBuilder / ForgetBuilder
91
+ retry.py RetryPolicy + with_retry (exponential backoff, server retry_after)
92
+ ```
93
+
94
+ ## HTTP tier
95
+
96
+ For hosted Brain (the Arc cloud gateway) or a self-hosted `brain-edge` edge, the
97
+ package also ships `BrainHttpClient` — a JSON-over-HTTP client with the same verb
98
+ surface, field names, and error shape as the Rust and TypeScript SDKs (the
99
+ canonical contract is [`../HTTP_CONTRACT.md`](../HTTP_CONTRACT.md)). Use it when
100
+ you talk to Brain through an HTTP edge and authenticate with an API key; use the
101
+ wire `BrainClient` above for a direct socket, streaming, transactions, and
102
+ typed-graph management. It has no third-party dependency — pure `urllib`.
103
+
104
+ ```python
105
+ from brain_db_sdk import BrainHttpClient
106
+
107
+ brain = BrainHttpClient(api_key, base_url="https://api.arc-labs.ai")
108
+ stored = brain.encode(text="the kettle whistled")
109
+ answer = brain.recall(query="what whistled?", max_results=3)
110
+ who = brain.whoami() # namespace + space_id + permissions
111
+ ```
112
+
113
+ Dependencies: `cbor2` (runtime), `pytest` (dev). CRC32C is pure Python.
114
+
115
+ The live HTTP edge smoke tests cover identity, capabilities, and a memory
116
+ encode/recall/list/forget lifecycle across all SDKs. Run them from the repo
117
+ root with `BRAIN_SDK_IT_HTTP=https://edge.example BRAIN_SDK_IT_HTTP_KEY=brain_…
118
+ scripts/edge-it.sh`.
119
+ License: Apache-2.0.
@@ -0,0 +1,95 @@
1
+ # brain-db-sdk (Python)
2
+
3
+ The Python client for the Brain memory database. Speaks Brain's BRN0 wire
4
+ protocol directly; no dependency on Brain's internal code.
5
+
6
+ **Status: typed-graph verbs (Phase 6).** The wire codec (Phase 1) is **verified
7
+ byte-for-byte against the shared conformance corpus** (all 86 `.bin`/`.json`
8
+ cases re-encode to identical bytes). On top of it, a synchronous connection
9
+ layer (a `transport` over a socket, a `Connection` running the handshake HELLO →
10
+ WELCOME → AUTH → AUTH_OK and request/response, a `BrainClient` holding the
11
+ negotiated session), the three v1 verbs with ergonomic builders (`encode()`,
12
+ `recall()` streaming to EOS / `recall_frames()`, `forget()`), a `with_retry`
13
+ helper + `RetryPolicy` (exponential backoff, server `retry_after_ms`), and the
14
+ typed-graph verbs: `create_entity()`, `create_statement()`, `create_relation()`,
15
+ `upload_schema()`, and `materialize_procedural()`; and the space/session registry
16
+ verbs: `create_space()` / `list_spaces()` / `delete_space()` and
17
+ `create_session()` / `list_sessions()` / `delete_session()` for managing the
18
+ per-request isolation unit (space) and conversation groupings (session) that a
19
+ trusted principal targets via `act_as`. `BrainClient` is built on a
20
+ `MuxConnection`: a background reader thread demultiplexes responses by
21
+ `stream_id`, so **every verb is concurrency-safe** and many requests run in
22
+ flight at once over one connection from multiple threads. A `Pool` opens a fixed
23
+ set of such connections and hands them out round-robin for socket-level
24
+ parallelism. Transparent reconnect and an `asyncio` client are later phases.
25
+
26
+ The full build plan is in the repo-root [`../PLAN.md`](../PLAN.md); the
27
+ layered architecture is in [`../ARCHITECTURE.md`](../ARCHITECTURE.md).
28
+
29
+ ```python
30
+ from brain_db_sdk import (
31
+ BrainClient, EncodeBuilder, RecallBuilder, ForgetBuilder, RetryPolicy, with_retry,
32
+ )
33
+
34
+ with BrainClient.connect("127.0.0.1", 7878) as client:
35
+ stored = client.encode(EncodeBuilder("the user prefers dark mode").build())
36
+ answer = client.recall(RecallBuilder("ui preferences").limit(5).build())
37
+ # answer.answer_kind is Single/Set (fact answer.values) or Episodic
38
+ # (memory answer.results); NoSubject/NoMemory means "don't know".
39
+ # Ride out transient ResourceExhausted/Unavailable; the stable request_id
40
+ # makes the resend idempotent.
41
+ req = ForgetBuilder(stored.memory_id).build()
42
+ with_retry(lambda: client.forget(req), RetryPolicy())
43
+ ```
44
+
45
+ Develop + verify against the corpus:
46
+
47
+ ```bash
48
+ python3 -m venv .venv && .venv/bin/pip install cbor2 pytest
49
+ PYTHONPATH=src .venv/bin/python -m pytest tests/ -q
50
+ ```
51
+
52
+ The integration suites run against a real server when `BRAIN_SDK_IT_DATA` is
53
+ set, and skip otherwise; `scripts/it-server.sh up` boots one and prints the
54
+ vars. Set `BRAIN_SDK_IT_REQUIRED=1` wherever a server is meant to be reachable
55
+ so a misconfigured one fails instead of reading as green.
56
+
57
+ Layout (folder-per-concern, mirroring the reference Rust SDK):
58
+
59
+ ```
60
+ src/brain_db_sdk/
61
+ wire/ frame + CBOR codec, opcodes, typed payloads (corpus-verified)
62
+ errors.py client error taxonomy (BrainError + subclasses)
63
+ transport.py sync read/write of whole frames over a socket
64
+ connection.py handshake + one-at-a-time request/response
65
+ client.py high-level BrainClient: connect, handshake, encode/recall/forget
66
+ verbs.py ergonomic EncodeBuilder / RecallBuilder / ForgetBuilder
67
+ retry.py RetryPolicy + with_retry (exponential backoff, server retry_after)
68
+ ```
69
+
70
+ ## HTTP tier
71
+
72
+ For hosted Brain (the Arc cloud gateway) or a self-hosted `brain-edge` edge, the
73
+ package also ships `BrainHttpClient` — a JSON-over-HTTP client with the same verb
74
+ surface, field names, and error shape as the Rust and TypeScript SDKs (the
75
+ canonical contract is [`../HTTP_CONTRACT.md`](../HTTP_CONTRACT.md)). Use it when
76
+ you talk to Brain through an HTTP edge and authenticate with an API key; use the
77
+ wire `BrainClient` above for a direct socket, streaming, transactions, and
78
+ typed-graph management. It has no third-party dependency — pure `urllib`.
79
+
80
+ ```python
81
+ from brain_db_sdk import BrainHttpClient
82
+
83
+ brain = BrainHttpClient(api_key, base_url="https://api.arc-labs.ai")
84
+ stored = brain.encode(text="the kettle whistled")
85
+ answer = brain.recall(query="what whistled?", max_results=3)
86
+ who = brain.whoami() # namespace + space_id + permissions
87
+ ```
88
+
89
+ Dependencies: `cbor2` (runtime), `pytest` (dev). CRC32C is pure Python.
90
+
91
+ The live HTTP edge smoke tests cover identity, capabilities, and a memory
92
+ encode/recall/list/forget lifecycle across all SDKs. Run them from the repo
93
+ root with `BRAIN_SDK_IT_HTTP=https://edge.example BRAIN_SDK_IT_HTTP_KEY=brain_…
94
+ scripts/edge-it.sh`.
95
+ License: Apache-2.0.
@@ -0,0 +1,229 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "brain-db-sdk"
7
+ version = "0.1.0" # x-release-please-version
8
+ description = "Python client SDK for the Brain memory database. Speaks Brain's BRN0 wire protocol directly over TCP."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Niraj Georgian" }]
14
+ keywords = ["brain", "memory", "ai-agents", "client", "database"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Database",
21
+ "Topic :: Software Development :: Libraries",
22
+ ]
23
+ dependencies = [
24
+ # CBOR (RFC 8949) payload maps. cbor2 distinguishes byte strings from
25
+ # arrays (required for id / [u8;N] fields) and exposes per-value
26
+ # minimal-float encoding, which the wire format needs for f32 fields.
27
+ # >=5.9 is a security floor, not a feature floor: cbor2 5.6-5.8 are
28
+ # vulnerable to CVE-2026-26209 (CVSS 7.5) -- uncontrolled recursion in
29
+ # loads() lets a peer crash the client with a <100KB deeply-nested payload.
30
+ # 5.9 added the nesting-depth cap that turns that into a clean
31
+ # CBORDecodeError. See tests/test_malformed.py, which pins the behaviour.
32
+ "cbor2>=5.9",
33
+ # CRC32C is implemented in pure Python (wire/crc32c.py) — no native or
34
+ # network dependency for a core checksum.
35
+ ]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/arc-labs-ai/brain-sdk"
39
+ Repository = "https://github.com/arc-labs-ai/brain-sdk"
40
+
41
+ [project.optional-dependencies]
42
+ dev = ["pytest>=8", "ruff>=0.16", "pyright>=1.1.400"]
43
+
44
+ [tool.ruff]
45
+ target-version = "py310"
46
+ # Matches the TypeScript SDK's Biome setting and the width this code was
47
+ # already written to. Ruff's default 88 would reflow 198 existing lines for no
48
+ # reason; 100 reflows 93 and they are genuinely long.
49
+ line-length = 100
50
+
51
+ [tool.ruff.format]
52
+ # The formatter half, which this package did not have. Rust has rustfmt and
53
+ # TypeScript now has Biome; leaving Python unformatted was the odd one out.
54
+ docstring-code-format = true
55
+
56
+ [tool.ruff.lint]
57
+ # Everything on, exceptions written down.
58
+ #
59
+ # The previous selection was ["F", "E9", "B"]. Running `--select ALL` produced
60
+ # ~3400 findings; the ones removed below are removed for a stated reason, with
61
+ # the count they produced, so the next person can see they were considered
62
+ # rather than never enabled. Starting from ALL also means a new ruff release
63
+ # arrives with its new rules already on, which is the same "no silent drift"
64
+ # property the protocol gates give the wire.
65
+ select = ["ALL"]
66
+
67
+ ignore = [
68
+ # -- the formatter owns these ------------------------------------------
69
+ "E501", # 299. line-too-long: `ruff format` decides line breaks.
70
+ "COM812", # 174. missing-trailing-comma: same.
71
+ "ISC001", # single-line-implicit-concat: conflicts with the formatter.
72
+ "ISC003", # explicit-string-concat: directly contradicts ISC004, which
73
+ # is kept. In a collection literal an *implicit* concat is
74
+ # one missing comma away from silently merging two elements,
75
+ # so the explicit `+` is the safer of the two.
76
+
77
+ # -- docstring style, not docstring absence -----------------------------
78
+ # This package is heavily documented; what pydocstyle objects to is the
79
+ # *shape*. The prose here is deliberately multi-paragraph and explanatory,
80
+ # and these rules would flatten it.
81
+ "D203", # incompatible with D211, which is the convention used.
82
+ "D205", # 211. blank line required after a one-line summary.
83
+ "D209", # 164. multi-line closing quotes on their own line.
84
+ "D213", # 285. multi-line summary on the second line: this codebase puts
85
+ # the summary on the first line (D212), which is the opposite.
86
+ "D401", # 21. imperative mood ("Returns the…" vs "Return the…").
87
+ "D400", # 1. first line must end with a period.
88
+ "D415", # 1. same, with more punctuation allowed.
89
+
90
+ # -- fights what this package is ----------------------------------------
91
+ "PLR2004", # 74. magic-value-comparison: opcodes, CBOR major types and
92
+ # frame offsets are magic numbers by definition.
93
+ "FBT001", # 26. boolean-typed positional argument, and
94
+ "FBT002", # 6. boolean default, and
95
+ "FBT003", # 91. boolean positional in a call — the wire dataclasses mirror
96
+ # the server's field order, which is not ours to reshape.
97
+ "TRY003", # 29. long message outside the exception class, and
98
+ "EM101", # 7. string literal in a raise, and
99
+ "EM102", # 22. f-string in a raise — a wire error should say what byte or
100
+ # field was wrong, at the point that knows.
101
+ "CPY001", # 49. missing copyright notice: the licence is in LICENSE.
102
+ "UP045", # 193. `Optional[X]` -> `X | None`, and
103
+ "UP007", # 2. the same for Union. These were required at the old >=3.9
104
+ # floor, where `X | Y` is not available at runtime and several
105
+ # of these modules evaluate annotations eagerly. At >=3.10 the
106
+ # syntax works, so the ignores are now a deliberate choice not
107
+ # to churn ~195 annotation sites rather than a hard constraint.
108
+ "PYI019", # 3. same TypeVar-instead-of-Self constraint as PYI034 below.
109
+ "PYI034", # 3. `__enter__` should return `Self` — which is 3.11+, while
110
+ # requires-python is >=3.10, and `typing_extensions` is not a
111
+ # dependency. A `TypeVar` bound to the class carries the same
112
+ # meaning and is what these use; ruff's autofix for this rule
113
+ # imports typing_extensions and breaks the install.
114
+ "TC001", # 1. and
115
+ "TC003", # 3. move typing-only imports into a TYPE_CHECKING block. The
116
+ # saving is a few microseconds of import time; the risk is a
117
+ # dataclass or a `get_type_hints` call resolving a name that
118
+ # is no longer there at runtime. Not worth it for this shape
119
+ # of code.
120
+ "D107", # 12. undocumented `__init__`: every one is a one-line
121
+ # constructor under a class docstring that already says what
122
+ # the type is and what it carries. A second docstring below
123
+ # it would restate the first.
124
+ "RUF022", # 1. `__all__` is grouped by tier (wire, http, client) with a
125
+ # comment on each group; alphabetising it would scatter the
126
+ # groups and orphan the comments.
127
+ "D105", # 8. undocumented magic method: `__enter__`/`__exit__`/`__iter__`
128
+ # mean exactly what the protocol says they mean.
129
+ "N818", # 11. exception names must end in "Error": these mirror the Rust
130
+ # SDK's variant names (VersionMismatch, ConnectionClosed) so
131
+ # the three SDKs read the same.
132
+
133
+ # -- thresholds, not defects --------------------------------------------
134
+ "PLR0913", # 7. too-many-arguments
135
+ "PLR0917", # 7. too-many-positional-arguments
136
+ "PLR0915", # 3. too-many-statements
137
+ "PLR0912", # 2. too-many-branches
138
+ "PLR0911", # 2. too-many-return-statements
139
+ "C901", # 3. complex-structure
140
+
141
+ # -- wrong for this code, on inspection ---------------------------------
142
+ "PERF203", # 4. try-except in a loop: every one is a retry or a
143
+ # best-effort cleanup, which is what the construct is for.
144
+ "S110", # 4. try-except-pass: all four are best-effort connection
145
+ # teardown, already carrying a comment saying so. A failure
146
+ # to close a socket we are discarding is not actionable.
147
+ ]
148
+
149
+ [tool.ruff.lint.per-file-ignores]
150
+ # The wire and HTTP type modules mirror the server's structs one-for-one. Their
151
+ # documentation is the protocol itself — `conformance/protocol.json` carries
152
+ # every field and serde attribute, and the corpus pins the bytes. A docstring
153
+ # on each of ~495 generated-equivalent `to_map`/`from_map` methods would
154
+ # restate the method name and bury the ones that do carry meaning.
155
+ "src/brain_db_sdk/wire/types.py" = [
156
+ "D101",
157
+ "D102",
158
+ "D105",
159
+ "D106",
160
+ "D107",
161
+ "RUF012",
162
+ ]
163
+ "src/brain_db_sdk/http/types.py" = ["D101", "D102", "D105", "D106", "D107"]
164
+
165
+ # Tests: `assert` is what pytest is built on, fixture data is camelCase because
166
+ # the wire is, and the feature folders deliberately have no `__init__.py` (the
167
+ # pytest importlib mode below is what makes that work).
168
+ "tests/**" = [
169
+ "S101", # 368. assert
170
+ "INP001", # 30. implicit namespace package
171
+ "ANN", # 111. missing annotations on test helpers
172
+ "D100",
173
+ "D101",
174
+ "D102",
175
+ "D103",
176
+ "D104",
177
+ "D107",
178
+ "N815", # 4. camelCase in class scope — JSON fixture keys
179
+ "N812", # 1. lowercase import aliased to non-lowercase
180
+ "PLC0415", # 3. import outside top-level — deliberate lazy imports
181
+ "E402", # 1. import not at top — after a guard
182
+ "PT018", # 15. composite assertion
183
+ "SLF001", # private member access: tests check internals on purpose
184
+ "S105",
185
+ "S106",
186
+ "S311",
187
+ ]
188
+
189
+ [tool.pytest.ini_options]
190
+ # importlib import mode lets the feature folders (tests/encode/, tests/recall/,
191
+ # …) each carry a `test_<feature>.py` without basename collisions against the
192
+ # flat offline suites (e.g. tests/test_handshake.py vs tests/handshake/…).
193
+ testpaths = ["tests"]
194
+ addopts = "--import-mode=importlib"
195
+ markers = [
196
+ "slow: builds a wheel; excluded from the default run with -m 'not slow'",
197
+ ]
198
+
199
+ [tool.hatch.build.targets.wheel]
200
+ packages = ["src/brain_db_sdk"]
201
+ # PEP 561: without this marker in the built wheel, a downstream type checker
202
+ # MUST ignore every annotation in the installed package — so all of the typing
203
+ # above would reach exactly nobody. `tests/test_py_typed.py` asserts it is
204
+ # present and listed here.
205
+ artifacts = ["src/brain_db_sdk/py.typed"]
206
+
207
+ [tool.pyright]
208
+ # The type checker the other two SDKs always had: Rust has the compiler,
209
+ # TypeScript has `tsc`, and Python had annotations that nothing verified.
210
+ #
211
+ # pyright rather than mypy. The original reason was that mypy 2.x refuses to
212
+ # target anything below 3.10 and the floor was 3.9, so mypy could not check the
213
+ # version we ship. At a >=3.10 floor that no longer applies, and pyright stays
214
+ # on its own merits: it is what Pylance runs, so what CI enforces is what a
215
+ # user sees in their editor.
216
+ include = ["src/brain_db_sdk"]
217
+ pythonVersion = "3.10"
218
+ # `standard`, not `strict`, and the difference is recorded rather than hidden:
219
+ # strict additionally reports 112 `reportUnknown*` diagnostics, essentially all
220
+ # of them in `wire/types.py`'s externally-tagged union helpers, where a
221
+ # `variant: str` selects which of several shapes `value` holds. Typing those
222
+ # fully means writing out every union arm; four of the eleven are done (see
223
+ # AuthCredentials, StatementValue, StatementObject, RetrieverSelection) and the
224
+ # rest are the same mechanical work. `standard` gates on every diagnostic that
225
+ # indicates an actual type error, which is what this is for; the count above is
226
+ # the honest size of what it does not yet cover.
227
+ typeCheckingMode = "standard"
228
+ # Reported as errors rather than warnings so CI actually gates on them.
229
+ reportMissingTypeStubs = "error"