nevarn-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.
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,6 @@
1
+ Nevarn SDK for Python (nevarn-sdk)
2
+ Copyright 2026 Binaries Fort AB
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+ The licence covers this software only. Use of the Nevarn platform it calls is
6
+ licensed separately, on the platform, by governed actions or by subscription.
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: nevarn-sdk
3
+ Version: 0.1.0
4
+ Summary: Thin client for the Nevarn platform API: a bot's intents, executions under Decionis policy, bounds, receipts and halt.
5
+ Author: Binaries Fort AB
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Documentation, https://nevarn.com/docs/sdk
8
+ Project-URL: Repository, https://github.com/orepos/Nevarn
9
+ Keywords: nevarn,trading,agents,decionis,bots
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.11
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ License-File: NOTICE
17
+ Requires-Dist: httpx<0.29,>=0.28.1
18
+ Dynamic: license-file
19
+
20
+ # nevarn-sdk (Python)
21
+
22
+ A thin client for the Nevarn platform API, for an operator's own bot and
23
+ servers. It adds no authority: a bot sends intents, never orders or keys, and
24
+ every method calls a route an `nvk_` API key is already scoped for. Contract:
25
+ `docs/strategy/Contract.md`; design: `docs/workplans/agent-sdk.design.md`.
26
+
27
+ Free to download, under the Apache License 2.0 (`LICENSE`, `NOTICE`). Using
28
+ the Nevarn platform it calls is licensed on the platform, by governed actions
29
+ or by subscription.
30
+
31
+ ```python
32
+ from datetime import datetime, timezone
33
+
34
+ import nevarn
35
+
36
+ client = nevarn.Client(baseUrl="https://<your platform API>") # key from NEVARN_API_KEY
37
+ print(client.getMandate().intents) # shadow mode, and the Decionis policy for each strategy
38
+ ruling = client.proposeIntent(
39
+ strategy="polymarket",
40
+ intentKey="momentum-1", # your idempotency key: reuse it to retry, never for other terms
41
+ intent={"token_id": "7132…", "side": "BUY", "maker_amount": 5_000_000,
42
+ "taker_amount": 10_000_000, "observed_at": datetime.now(timezone.utc)},
43
+ )
44
+ print(ruling.verdict, ruling.wouldExecute, ruling.reasons) # executed is always False in shadow
45
+
46
+ # With an `execute` key: on paper in the tenant's Sandbox, live in Production.
47
+ execution = client.executeIntent(strategy="polymarket", intentKey="momentum-2", intent={...})
48
+ print(execution.environment, execution.state, execution.paper) # "sandbox", "paper_filled", the fill
49
+ print(client.getExecution(execution.id).state) # Production: queued, then submitted, confirmed
50
+ ```
51
+
52
+ | Method | Route | Key scope | Today |
53
+ | --- | --- | --- | --- |
54
+ | `proposeIntent` | `POST /machine/intents` | `intents` | Shadow ruling; nothing is sent to a venue |
55
+ | `executeIntent` | `POST /machine/executions` | `execute` | Sandbox: a paper fill and shadow rulings. Production: queued, ruled in ENFORCEMENT at the venue, sent with the tenant's venue credentials |
56
+ | `getExecution` | `GET /machine/executions/{id}` | `execute` | One execution and its current state |
57
+ | `getMandate` | `GET /machine/mandate` | `read` | Limits, signing grants, payables policy, intent policies, the execution environment and key limits, this month's governed actions |
58
+ | `getReceipt` | `GET /machine/receipts/{id}` | `read` | One execution receipt, by the execution's id |
59
+ | `halt` | `POST /machine/halt` | `halt` | Turns all signing off and stops the bots' unfinished executions; there is no resume |
60
+ | `requestSpend` | `POST /machine/invoices` | `invoices` | Files a supplier invoice |
61
+
62
+ `proposeIntent` refuses, before sending, an intent with a field named like a
63
+ secret (`private_key`, `signature`, `apiKey`, …) or a value shaped like a
64
+ private key. A reused intent key with other terms raises `IntentConflict`
65
+ (409), as does an intent sent while the deployment has shadow mode off.
66
+
67
+ `executeIntent` takes the same terms and runs the same local check. Where the
68
+ order goes is the tenant's environment, never the bot's choice. An `execute`
69
+ key is minted by an owner with its own limits (orders a minute, the largest
70
+ order, a 24-hour total, in USDC minor units), and it executes `polymarket` and
71
+ `sports` intents. A refusal raises `ExecutionRefused` (409) whose `code` says
72
+ why: `key_order_limit_exceeded`, `key_daily_limit_exceeded`,
73
+ `tenant_order_limit_exceeded`, `tenant_halted`, `intent_replayed`,
74
+ `intent_key_reused`, `key_minted_without_wallet` (a key minted from a password
75
+ sign-in asked for Production; it executes in Sandbox only), `strategy_not_executable`,
76
+ `policy_not_published`, `policy_mapping_unpublished`, `runtime_adapter_unpinned` or
77
+ `authority_not_configured`. The key's minute window raises `RateLimited` (429).
78
+
79
+ `requestSpend` files a supplier invoice; it is not a request for raw funds. The
80
+ platform's payables policy decides the outcome: the vendor must already be
81
+ verified and the destination must be its payout address; tiers 1–2 are paid
82
+ automatically, tier 3 waits for an owner, tier 4 is paid by the customer. A
83
+ duplicate raises `Conflict` (409).
84
+
85
+ ## Guarantees
86
+
87
+ - The base URL is required and must be `https` (plain `http` only on
88
+ `127.0.0.1`, `localhost` or `[::1]`). There is no default.
89
+ - The key comes only from the constructor or `NEVARN_API_KEY`, must be an
90
+ `nvk_` key, and never appears in `repr`, errors or logs. Session tokens are
91
+ refused.
92
+ - Redirects are refused, the timeout is 5 seconds, and errors carry only the
93
+ status, the platform error code and the path template.
94
+ - There is no method for limits, resume, keys, vendors or approvals, and
95
+ `halt` takes only an optional reason.
96
+
97
+ ## Tests
98
+
99
+ ```bash
100
+ python -m pytest tests -q
101
+ ```
102
+
103
+ The platform contract tests are `apps/platform/tests/test_sdk_contract.py`
104
+ and `test_shadowbot_example.py`, which runs `examples/shadowbot` through the
105
+ real app.
106
+
107
+ ## Licence and release
108
+
109
+ Apache License 2.0 (`LICENSE`; `NOTICE` names Binaries Fort AB). The licence
110
+ covers this client only; the platform's use is licensed on the platform, by
111
+ governed actions or subscription.
112
+
113
+ Publishing stays the owner's: PyPI ownership of `nevarn-sdk` and the release
114
+ workflow. Until then the `Private :: Do Not Upload` classifier makes PyPI
115
+ refuse an upload; the owner removes it in the release change.
@@ -0,0 +1,96 @@
1
+ # nevarn-sdk (Python)
2
+
3
+ A thin client for the Nevarn platform API, for an operator's own bot and
4
+ servers. It adds no authority: a bot sends intents, never orders or keys, and
5
+ every method calls a route an `nvk_` API key is already scoped for. Contract:
6
+ `docs/strategy/Contract.md`; design: `docs/workplans/agent-sdk.design.md`.
7
+
8
+ Free to download, under the Apache License 2.0 (`LICENSE`, `NOTICE`). Using
9
+ the Nevarn platform it calls is licensed on the platform, by governed actions
10
+ or by subscription.
11
+
12
+ ```python
13
+ from datetime import datetime, timezone
14
+
15
+ import nevarn
16
+
17
+ client = nevarn.Client(baseUrl="https://<your platform API>") # key from NEVARN_API_KEY
18
+ print(client.getMandate().intents) # shadow mode, and the Decionis policy for each strategy
19
+ ruling = client.proposeIntent(
20
+ strategy="polymarket",
21
+ intentKey="momentum-1", # your idempotency key: reuse it to retry, never for other terms
22
+ intent={"token_id": "7132…", "side": "BUY", "maker_amount": 5_000_000,
23
+ "taker_amount": 10_000_000, "observed_at": datetime.now(timezone.utc)},
24
+ )
25
+ print(ruling.verdict, ruling.wouldExecute, ruling.reasons) # executed is always False in shadow
26
+
27
+ # With an `execute` key: on paper in the tenant's Sandbox, live in Production.
28
+ execution = client.executeIntent(strategy="polymarket", intentKey="momentum-2", intent={...})
29
+ print(execution.environment, execution.state, execution.paper) # "sandbox", "paper_filled", the fill
30
+ print(client.getExecution(execution.id).state) # Production: queued, then submitted, confirmed
31
+ ```
32
+
33
+ | Method | Route | Key scope | Today |
34
+ | --- | --- | --- | --- |
35
+ | `proposeIntent` | `POST /machine/intents` | `intents` | Shadow ruling; nothing is sent to a venue |
36
+ | `executeIntent` | `POST /machine/executions` | `execute` | Sandbox: a paper fill and shadow rulings. Production: queued, ruled in ENFORCEMENT at the venue, sent with the tenant's venue credentials |
37
+ | `getExecution` | `GET /machine/executions/{id}` | `execute` | One execution and its current state |
38
+ | `getMandate` | `GET /machine/mandate` | `read` | Limits, signing grants, payables policy, intent policies, the execution environment and key limits, this month's governed actions |
39
+ | `getReceipt` | `GET /machine/receipts/{id}` | `read` | One execution receipt, by the execution's id |
40
+ | `halt` | `POST /machine/halt` | `halt` | Turns all signing off and stops the bots' unfinished executions; there is no resume |
41
+ | `requestSpend` | `POST /machine/invoices` | `invoices` | Files a supplier invoice |
42
+
43
+ `proposeIntent` refuses, before sending, an intent with a field named like a
44
+ secret (`private_key`, `signature`, `apiKey`, …) or a value shaped like a
45
+ private key. A reused intent key with other terms raises `IntentConflict`
46
+ (409), as does an intent sent while the deployment has shadow mode off.
47
+
48
+ `executeIntent` takes the same terms and runs the same local check. Where the
49
+ order goes is the tenant's environment, never the bot's choice. An `execute`
50
+ key is minted by an owner with its own limits (orders a minute, the largest
51
+ order, a 24-hour total, in USDC minor units), and it executes `polymarket` and
52
+ `sports` intents. A refusal raises `ExecutionRefused` (409) whose `code` says
53
+ why: `key_order_limit_exceeded`, `key_daily_limit_exceeded`,
54
+ `tenant_order_limit_exceeded`, `tenant_halted`, `intent_replayed`,
55
+ `intent_key_reused`, `key_minted_without_wallet` (a key minted from a password
56
+ sign-in asked for Production; it executes in Sandbox only), `strategy_not_executable`,
57
+ `policy_not_published`, `policy_mapping_unpublished`, `runtime_adapter_unpinned` or
58
+ `authority_not_configured`. The key's minute window raises `RateLimited` (429).
59
+
60
+ `requestSpend` files a supplier invoice; it is not a request for raw funds. The
61
+ platform's payables policy decides the outcome: the vendor must already be
62
+ verified and the destination must be its payout address; tiers 1–2 are paid
63
+ automatically, tier 3 waits for an owner, tier 4 is paid by the customer. A
64
+ duplicate raises `Conflict` (409).
65
+
66
+ ## Guarantees
67
+
68
+ - The base URL is required and must be `https` (plain `http` only on
69
+ `127.0.0.1`, `localhost` or `[::1]`). There is no default.
70
+ - The key comes only from the constructor or `NEVARN_API_KEY`, must be an
71
+ `nvk_` key, and never appears in `repr`, errors or logs. Session tokens are
72
+ refused.
73
+ - Redirects are refused, the timeout is 5 seconds, and errors carry only the
74
+ status, the platform error code and the path template.
75
+ - There is no method for limits, resume, keys, vendors or approvals, and
76
+ `halt` takes only an optional reason.
77
+
78
+ ## Tests
79
+
80
+ ```bash
81
+ python -m pytest tests -q
82
+ ```
83
+
84
+ The platform contract tests are `apps/platform/tests/test_sdk_contract.py`
85
+ and `test_shadowbot_example.py`, which runs `examples/shadowbot` through the
86
+ real app.
87
+
88
+ ## Licence and release
89
+
90
+ Apache License 2.0 (`LICENSE`; `NOTICE` names Binaries Fort AB). The licence
91
+ covers this client only; the platform's use is licensed on the platform, by
92
+ governed actions or subscription.
93
+
94
+ Publishing stays the owner's: PyPI ownership of `nevarn-sdk` and the release
95
+ workflow. Until then the `Private :: Do Not Upload` classifier makes PyPI
96
+ refuse an upload; the owner removes it in the release change.
@@ -0,0 +1,156 @@
1
+ """The Nevarn client: the routes an API key can call, and nothing that widens its bounds.
2
+
3
+ ``proposeIntent`` sends a bot's intent for a shadow ruling (scope
4
+ ``intents``); ``executeIntent`` and ``getExecution`` have one executed under
5
+ Decionis policy within the key's limits, on paper in Sandbox and live in
6
+ Production (``execute``); ``getMandate`` and ``getReceipt`` read the bot's
7
+ bounds and its execution receipts (``read``); ``halt`` turns the tenant's
8
+ signing off (``halt``); ``requestSpend`` files a supplier invoice
9
+ (``invoices``).
10
+ There is deliberately no method for limits, resume, keys, vendors or
11
+ approvals: those routes take an owner's session, and this client refuses
12
+ sessions.
13
+
14
+ Transport conventions follow the agents' tenant feed: no redirects are
15
+ followed, the timeout is 5 seconds, and neither the upstream body nor the
16
+ transport exception is re-raised, because both can carry the request.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import logging
22
+ from datetime import datetime
23
+ from uuid import UUID
24
+
25
+ import httpx
26
+
27
+ from .Config import ApiKey, BaseUrl
28
+ from .Errors import NevarnError, RateLimited, RedirectRefused, TransportError, UnexpectedResponse, forStatus
29
+ from .Execution import PATH as EXECUTION_PATH
30
+ from .Execution import Execution, ExecutionGate
31
+ from .Intent import PATH as INTENT_PATH
32
+ from .Intent import IntentRequest, IntentRuling
33
+ from .Mandate import HALT_PATH, Halted, HaltRequest, Mandate
34
+ from .Mandate import PATH as MANDATE_PATH
35
+ from .Receipt import Receipt, ReceiptGate
36
+ from .Spend import PATH as SPEND_PATH
37
+ from .Spend import Invoice, SpendRequest
38
+ from .Version import USER_AGENT
39
+
40
+ TIMEOUT_SECONDS = 5.0
41
+ log = logging.getLogger("nevarn")
42
+
43
+
44
+ class Client:
45
+ def __init__(self, *, baseUrl: str, apiKey: str | None = None, httpClient: httpx.Client | None = None) -> None:
46
+ self.baseUrl = BaseUrl(baseUrl)
47
+ self._key = ApiKey(apiKey)
48
+ self._http = httpClient if httpClient is not None else httpx.Client(follow_redirects=False)
49
+ self._ownsHttp = httpClient is None
50
+
51
+ def __repr__(self) -> str:
52
+ return f"Client(baseUrl={self.baseUrl.value!r}, apiKey=<redacted>)"
53
+
54
+ def __enter__(self) -> Client:
55
+ return self
56
+
57
+ def __exit__(self, *_exc) -> None:
58
+ self.close()
59
+
60
+ def close(self) -> None:
61
+ if self._ownsHttp:
62
+ self._http.close()
63
+
64
+ def requestSpend(
65
+ self,
66
+ *,
67
+ vendorId: UUID | str,
68
+ invoiceNumber: str,
69
+ amountMinor: int,
70
+ destinationAddress: str,
71
+ assetCode: str = "USDC",
72
+ chainId: int = 137,
73
+ dueAt: datetime | None = None,
74
+ proofHash: str | None = None,
75
+ ) -> Invoice:
76
+ """File an invoice; the platform's payables policy decides what is paid."""
77
+ request = SpendRequest(
78
+ vendorId=vendorId, invoiceNumber=invoiceNumber, amountMinor=amountMinor,
79
+ destinationAddress=destinationAddress, assetCode=assetCode, chainId=chainId,
80
+ dueAt=dueAt, proofHash=proofHash,
81
+ )
82
+ status, data = self._send("POST", SPEND_PATH, request.body())
83
+ return Invoice.fromJson(data, status=status)
84
+
85
+ def proposeIntent(self, *, strategy: str, intentKey: str, intent: dict) -> IntentRuling:
86
+ """Ask for a shadow ruling on an intent. Nothing is sent to a venue; reuse a key to retry safely."""
87
+ request = IntentRequest(strategy=strategy, intentKey=intentKey, intent=intent)
88
+ status, data = self._send("POST", INTENT_PATH, request.body())
89
+ return IntentRuling.fromJson(data, status=status)
90
+
91
+ def executeIntent(self, *, strategy: str, intentKey: str, intent: dict) -> Execution:
92
+ """Execute an intent within the key's limits: on paper in Sandbox, live in Production. Reuse a key to retry."""
93
+ request = IntentRequest(strategy=strategy, intentKey=intentKey, intent=intent)
94
+ status, data = self._send("POST", EXECUTION_PATH, request.body())
95
+ return Execution.fromJson(data, status=status)
96
+
97
+ def getExecution(self, executionId: UUID | str) -> Execution:
98
+ """One execution, by the id ``executeIntent`` returned, with its current state."""
99
+ path = ExecutionGate.path(executionId)
100
+ status, data = self._send("GET", path)
101
+ return Execution.fromJson(data, status=status, path=path)
102
+
103
+ def getMandate(self) -> Mandate:
104
+ """The bot's bounds as the console shows them. Read-only."""
105
+ status, data = self._send("GET", MANDATE_PATH)
106
+ return Mandate.fromJson(data, status=status)
107
+
108
+ def getReceipt(self, receiptId: UUID | str) -> Receipt:
109
+ """One execution receipt, by its execution's id."""
110
+ path = ReceiptGate.path(receiptId)
111
+ status, data = self._send("GET", path)
112
+ return Receipt.fromJson(data, status=status)
113
+
114
+ def halt(self, reason: str | None = None) -> Halted:
115
+ """Turn all of the tenant's signing off. Idempotent. There is no resume."""
116
+ status, data = self._send("POST", HALT_PATH, HaltRequest.body(reason))
117
+ return Halted.fromJson(data, status=status)
118
+
119
+ def _send(self, method: str, path: str, body: dict | None = None) -> tuple[int, object]:
120
+ headers = {
121
+ "Authorization": self._key.authorization(),
122
+ "User-Agent": USER_AGENT,
123
+ "Accept": "application/json",
124
+ }
125
+ try:
126
+ response = self._http.request(
127
+ method, self.baseUrl.join(path), json=body if method != "GET" else None, headers=headers,
128
+ timeout=TIMEOUT_SECONDS, follow_redirects=False,
129
+ )
130
+ except httpx.HTTPError:
131
+ log.warning("nevarn %s %s unreachable", method, path)
132
+ raise TransportError(path=path) from None
133
+ status = response.status_code
134
+ log.debug("nevarn %s %s -> %s", method, path, status)
135
+ if 300 <= status < 400:
136
+ raise RedirectRefused(status=status, path=path)
137
+ try:
138
+ data = response.json()
139
+ except ValueError:
140
+ data = None
141
+ if status in (200, 201):
142
+ if data is None:
143
+ raise UnexpectedResponse(status=status, path=path)
144
+ return status, data
145
+ raise self._failure(status, path, data, response.headers.get("retry-after"))
146
+
147
+ @staticmethod
148
+ def _failure(status: int, path: str, data: object, retryAfter: str | None) -> NevarnError:
149
+ error = data.get("error") if isinstance(data, dict) else None
150
+ code = error.get("code") if isinstance(error, dict) else None
151
+ code = code if isinstance(code, str) else None
152
+ kind = forStatus(status, path)
153
+ if kind is RateLimited:
154
+ seconds = int(retryAfter) if retryAfter and retryAfter.isdigit() else None
155
+ return RateLimited(status=status, code=code, path=path, retryAfter=seconds)
156
+ return kind(status=status, code=code, path=path)
@@ -0,0 +1,76 @@
1
+ """Where the client talks and what it presents: both explicit, both checked.
2
+
3
+ There is no default base URL, so a test or a script cannot reach production
4
+ by leaving one out, and plain http is accepted only for loopback. The key is
5
+ an ``nvk_`` merchant key from the constructor or ``NEVARN_API_KEY`` and
6
+ nothing else: a session token is refused outright, because an owner session
7
+ can raise the very limits an agent is supposed to be bounded by.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import re
14
+ from urllib.parse import urlsplit
15
+
16
+ from .Errors import ConfigurationError, SessionTokenRefused
17
+
18
+ ENV_KEY = "NEVARN_API_KEY"
19
+ LOOPBACK = frozenset({"127.0.0.1", "localhost", "::1"})
20
+ _KEY = re.compile(r"nvk_[A-Za-z0-9_-]{16,128}")
21
+ #: A platform session (base64url JSON payload + "." + signature) or a JWT:
22
+ #: either way a JSON object first, which base64url-encodes to "eyJ".
23
+ _SESSION = re.compile(r"eyJ[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+){1,2}")
24
+
25
+
26
+ class BaseUrl:
27
+ """An https origin (optionally with a path prefix), or http on loopback."""
28
+
29
+ __slots__ = ("value",)
30
+
31
+ def __init__(self, raw: str) -> None:
32
+ if not isinstance(raw, str) or not raw.strip():
33
+ raise ConfigurationError()
34
+ parts = urlsplit(raw.strip())
35
+ try:
36
+ parts.port
37
+ except ValueError:
38
+ raise ConfigurationError() from None
39
+ host = (parts.hostname or "").lower()
40
+ secure = parts.scheme == "https" or (parts.scheme == "http" and host in LOOPBACK)
41
+ if not host or not secure or parts.username or parts.password or parts.query or parts.fragment:
42
+ raise ConfigurationError()
43
+ self.value = f"{parts.scheme}://{parts.netloc}{parts.path.rstrip('/')}"
44
+
45
+ def join(self, path: str) -> str:
46
+ return self.value + path
47
+
48
+ def __repr__(self) -> str:
49
+ return f"BaseUrl({self.value!r})"
50
+
51
+
52
+ class ApiKey:
53
+ """The secret, kept out of repr, str and equality."""
54
+
55
+ __slots__ = ("_secret",)
56
+
57
+ def __init__(self, secret: str | None) -> None:
58
+ if secret is None:
59
+ secret = os.environ.get(ENV_KEY)
60
+ if not isinstance(secret, str) or not secret.strip():
61
+ raise ConfigurationError()
62
+ secret = secret.strip()
63
+ token = secret[7:].strip() if secret.lower().startswith("bearer ") else secret
64
+ if _SESSION.fullmatch(token):
65
+ raise SessionTokenRefused()
66
+ if not _KEY.fullmatch(secret):
67
+ raise ConfigurationError()
68
+ self._secret = secret
69
+
70
+ def authorization(self) -> str:
71
+ return f"Bearer {self._secret}"
72
+
73
+ def __repr__(self) -> str:
74
+ return "ApiKey(<redacted>)"
75
+
76
+ __str__ = __repr__