nps-lib 1.0.0a1__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.
@@ -0,0 +1,188 @@
1
+ Metadata-Version: 2.4
2
+ Name: nps-lib
3
+ Version: 1.0.0a1
4
+ Summary: Python SDK for the Neural Protocol Suite (NPS)
5
+ Author: LabAcacia / INNO LOTUS PTY LTD
6
+ License: Apache-2.0
7
+ License-File: LICENSE
8
+ License-File: NOTICE
9
+ Keywords: agent,ai,neural-protocol-suite,nps,protocol
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Internet :: WWW/HTTP
18
+ Classifier: Topic :: Software Development :: Libraries
19
+ Requires-Python: >=3.11
20
+ Requires-Dist: cryptography>=43.0.0
21
+ Requires-Dist: httpx>=0.27.0
22
+ Requires-Dist: msgpack>=1.0.8
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
25
+ Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
26
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
27
+ Requires-Dist: respx>=0.21.0; extra == 'dev'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # NPS Python SDK (`nps-sdk`)
31
+
32
+ Python client library for the **Neural Protocol Suite (NPS)** — a complete internet protocol stack designed for AI agents and models.
33
+
34
+ PyPI package: `nps-sdk` | Python namespace: `nps_sdk`
35
+
36
+ ## Status
37
+
38
+ **v0.1.0 — Phase 1 initial release (Alpha)**
39
+
40
+ Covers NCP + NWP frames and async client, NIP identity management.
41
+
42
+ ## Requirements
43
+
44
+ - Python 3.11+
45
+ - Dependencies: `msgpack`, `httpx`, `cryptography`
46
+
47
+ ## Installation
48
+
49
+ ```bash
50
+ pip install nps-sdk
51
+ ```
52
+
53
+ For development:
54
+
55
+ ```bash
56
+ pip install "nps-sdk[dev]"
57
+ ```
58
+
59
+ ## Modules
60
+
61
+ | Module | Description |
62
+ |--------|-------------|
63
+ | `nps_sdk.core` | Frame header, codec (Tier-1 JSON / Tier-2 MsgPack), anchor cache, exceptions |
64
+ | `nps_sdk.ncp` | NCP frames: AnchorFrame, DiffFrame, StreamFrame, CapsFrame, ErrorFrame |
65
+ | `nps_sdk.nwp` | NWP frames: QueryFrame, ActionFrame; async `NwpClient` |
66
+ | `nps_sdk.nip` | NIP frames: IdentFrame, RevokeFrame; `NipIdentity` (Ed25519 key management) |
67
+
68
+ ## Quick Start
69
+
70
+ ### Encoding / Decoding NCP Frames
71
+
72
+ ```python
73
+ from nps_sdk.core.codec import NpsFrameCodec
74
+ from nps_sdk.core.registry import FrameRegistry
75
+ from nps_sdk.ncp.frames import AnchorFrame, FrameSchema, SchemaField
76
+
77
+ registry = FrameRegistry.create_default()
78
+ codec = NpsFrameCodec(registry)
79
+
80
+ schema = FrameSchema(fields=(
81
+ SchemaField(name="id", type="uint64"),
82
+ SchemaField(name="price", type="decimal", semantic="commerce.price.usd"),
83
+ ))
84
+ frame = AnchorFrame(anchor_id="sha256:...", schema=schema)
85
+
86
+ wire = codec.encode(frame) # bytes — Tier-2 MsgPack by default
87
+ result = codec.decode(wire) # → AnchorFrame
88
+ ```
89
+
90
+ ### Anchor Cache (Schema Deduplication)
91
+
92
+ ```python
93
+ from nps_sdk.core.cache import AnchorFrameCache
94
+
95
+ cache = AnchorFrameCache()
96
+ anchor_id = cache.set(frame) # stores; returns canonical sha256 anchor_id
97
+ frame = cache.get_required(anchor_id)
98
+ ```
99
+
100
+ ### Querying a Memory Node (async)
101
+
102
+ ```python
103
+ import asyncio
104
+ from nps_sdk.nwp import NwpClient, QueryFrame
105
+
106
+ async def main():
107
+ async with NwpClient("https://node.example.com") as client:
108
+ caps = await client.query(
109
+ QueryFrame(anchor_ref="sha256:...", limit=50)
110
+ )
111
+ print(caps.count, caps.data)
112
+
113
+ asyncio.run(main())
114
+ ```
115
+
116
+ ### Invoking an Action Node (async)
117
+
118
+ ```python
119
+ from nps_sdk.nwp import NwpClient, ActionFrame
120
+
121
+ async with NwpClient("https://node.example.com") as client:
122
+ result = await client.invoke(
123
+ ActionFrame(action_id="orders.create", params={"sku": "X-101", "qty": 1})
124
+ )
125
+ ```
126
+
127
+ ### NIP Identity Management
128
+
129
+ ```python
130
+ from nps_sdk.nip.identity import NipIdentity
131
+
132
+ # Generate and save an encrypted Ed25519 keypair
133
+ identity = NipIdentity.generate("ca.key", passphrase="my-secret")
134
+
135
+ # Load from file
136
+ identity = NipIdentity()
137
+ identity.load("ca.key", passphrase="my-secret")
138
+
139
+ # Sign a NIP frame payload (canonical JSON, no 'signature' field)
140
+ sig = identity.sign(ident_frame.unsigned_dict())
141
+
142
+ # Verify
143
+ ok = NipIdentity.verify_signature(identity.pub_key_string, payload, sig)
144
+ ```
145
+
146
+ ## Architecture
147
+
148
+ ```
149
+ nps_sdk/
150
+ ├── core/ # Wire primitives (FrameHeader, codec, cache, exceptions)
151
+ ├── ncp/ # NCP frames (0x01–0x0F)
152
+ ├── nwp/ # NWP frames (0x10–0x1F) + async HTTP client
153
+ └── nip/ # NIP frames (0x20–0x2F) + Ed25519 identity
154
+ ```
155
+
156
+ ### Frame Encoding Tiers
157
+
158
+ | Tier | Value | Description |
159
+ |------|-------|-------------|
160
+ | Tier-1 JSON | `0x00` | UTF-8 JSON. Development / compatibility. |
161
+ | Tier-2 MsgPack | `0x01` | MessagePack binary. ~60% smaller. **Production default.** |
162
+
163
+ ### NWP HTTP Overlay Mode
164
+
165
+ `NwpClient` communicates via HTTP with `Content-Type: application/x-nps-frame`.
166
+ Sub-paths per operation:
167
+
168
+ | Operation | Path | Request Frame | Response Frame |
169
+ |-----------|------|---------------|----------------|
170
+ | Schema anchor | `POST /anchor` | AnchorFrame | 204 |
171
+ | Structured query | `POST /query` | QueryFrame | CapsFrame |
172
+ | Streaming query | `POST /stream` | QueryFrame | StreamFrame chunks |
173
+ | Action invocation | `POST /invoke` | ActionFrame | raw result or AsyncActionResponse |
174
+
175
+ ## Running Tests
176
+
177
+ ```bash
178
+ pytest # all tests + coverage report
179
+ pytest -k test_nip # NIP tests only
180
+ ```
181
+
182
+ Coverage target: ≥ 90 %.
183
+
184
+ ## License
185
+
186
+ Apache 2.0 — see [LICENSE](../../LICENSE).
187
+
188
+ Copyright 2026 INNO LOTUS PTY LTD
@@ -0,0 +1,28 @@
1
+ nps_sdk/__init__.py,sha256=ZQhAUgAVtJHVnZZHIkN0pszdAELIm5uG5t8D88EMaUo,338
2
+ nps_sdk/core/__init__.py,sha256=l4f2hSSFtm_kv4Py7FOk9qnh9nwRY8pKZ7Sl5f6KYds,786
3
+ nps_sdk/core/cache.py,sha256=C-zzAYGL2AhOCv4WzFsBQk1XtiiLrAtnVPeW8GBxX3M,5078
4
+ nps_sdk/core/codec.py,sha256=ihoJwvXeBGfXAlP4ahzsTnJjqzPdM7je9RUNacx5Nb4,7958
5
+ nps_sdk/core/exceptions.py,sha256=oJJL8Tt9a8OR1yMRx8vvoLJXiwTbMru-MMV3CBTF2d4,1117
6
+ nps_sdk/core/frames.py,sha256=pwUuObgRgPi_Qa-Wdj62iObO-KnQM_ZbmZgyMsB02Oo,7064
7
+ nps_sdk/core/registry.py,sha256=bQ06Lkq_JqSfcNzim9odAWjXQFudItRqip9X5WuySxs,3086
8
+ nps_sdk/ncp/__init__.py,sha256=TmCVpzRxuUQhkiF9G2vNiXD7RYcE4zjqK5jsMIV7dNI,474
9
+ nps_sdk/ncp/frames.py,sha256=oBEJOhFxg9vb_8n_GzAagQoQvHW7nCqGkY6yEqmqUDQ,10248
10
+ nps_sdk/ndp/__init__.py,sha256=3Fj7JWPnrzDDqCoXhG34WjWbY49RwDLD8WhUaj-3VK0,651
11
+ nps_sdk/ndp/frames.py,sha256=89IbDsL5MJsZKBLYlJMEFgL8RZgaVCAchkdXLjI8w9U,8492
12
+ nps_sdk/ndp/registry.py,sha256=ISBCjNKeea6m6Wo7udZlwFlpV4iZB9uan3sOgG283G8,5481
13
+ nps_sdk/ndp/validator.py,sha256=3w-11KoJmm_Y4SljSr0ABOQA9gwFTdZwNNIX5yumVVw,3411
14
+ nps_sdk/nip/__init__.py,sha256=ejV1-cLcjFDUYHTXXOisf2m-lg324F9z_u0yi05Yv0g,358
15
+ nps_sdk/nip/frames.py,sha256=wp2qjYtngi3dEF0nkEh4IP2Ee_Y1OSIRbJpgmdPGx2c,5493
16
+ nps_sdk/nip/identity.py,sha256=yXWRt4VEBESneUUq5gS3JuvGtgCK5RS3Jx7NWWTbhWI,9768
17
+ nps_sdk/nop/__init__.py,sha256=g3s1UrMbLvNbnSuM_oVyWg0B_4NP6q4pNAXuvo8YhD8,892
18
+ nps_sdk/nop/client.py,sha256=sOULJd6mZvV8OIKanYpACGsyzD-a-tKjAU5O5RrCPLs,6592
19
+ nps_sdk/nop/frames.py,sha256=xqdwFMa7OIaZNo-aOJ07CdpEsHmLT_zEAp6I0abZw24,10604
20
+ nps_sdk/nop/models.py,sha256=Q1bDmi7VEOi08DJ7Lw-uU4BZH0ayeH4ZbK9LqzRFH74,8409
21
+ nps_sdk/nwp/__init__.py,sha256=8QTYY45q40ZCLnq3atvU8AATAjwB0I9ek4Icw0M3RzU,467
22
+ nps_sdk/nwp/client.py,sha256=Iqh92mKb_5rrU1rOMQkc_tkPQO1Ri9sFs6JyboBpx8Y,6196
23
+ nps_sdk/nwp/frames.py,sha256=dCZ-9dUW4P5wi1phkf9MexCN-IrTH7cYeUvc0lwJ80M,6720
24
+ nps_lib-1.0.0a1.dist-info/METADATA,sha256=706n3aIK3IWnN7XqzC4VBe98-DCUAQJOWJQ645CI5TI,5433
25
+ nps_lib-1.0.0a1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
26
+ nps_lib-1.0.0a1.dist-info/licenses/LICENSE,sha256=H8oTbSGdbLw_zMYPqxTW_cSeSvnpT9ABu4YOgrQj2Bk,9367
27
+ nps_lib-1.0.0a1.dist-info/licenses/NOTICE,sha256=znLdIz2x6w42ncuit2Tcyj-fcvZWg8t_ScPuzPX51I8,287
28
+ nps_lib-1.0.0a1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,170 @@
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 made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of recording and
55
+ managing Contributions to the Work, but excluding communication that is
56
+ conspicularly marked or otherwise designated in writing by the copyright
57
+ owner as "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any
81
+ Contributor's Work constitutes direct or contributory patent
82
+ infringement, then any patent licenses granted to You under this
83
+ License for that Work shall terminate as of the date such litigation
84
+ is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or in addition to the
115
+ NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the License.
117
+
118
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
119
+ any Contribution intentionally submitted for inclusion in the Work
120
+ by You to the Licensor shall be under the terms and conditions of
121
+ this License, without any additional terms or conditions.
122
+
123
+ 6. Trademarks. This License does not grant permission to use the trade
124
+ names, trademarks, service marks, or product names of the Licensor,
125
+ except as required for reasonable and customary use in describing the
126
+ origin of the Work and reproducing the content of the NOTICE file.
127
+
128
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed
129
+ to in writing, Licensor provides the Work (and each Contributor
130
+ provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES
131
+ OR CONDITIONS OF ANY KIND, either express or implied, including,
132
+ without limitation, any warranties or conditions of TITLE,
133
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
134
+ PURPOSE. You are solely responsible for determining the
135
+ appropriateness of using or reproducing the Work and assume any
136
+ risks associated with Your exercise of permissions under this License.
137
+
138
+ 8. Limitation of Liability. In no event and under no legal theory,
139
+ whether in tort (including negligence), contract, or otherwise,
140
+ unless required by applicable law (such as deliberate and grossly
141
+ negligent acts) or agreed to in writing, shall any Contributor be
142
+ liable to You for damages, including any direct, indirect, special,
143
+ incidental, or exemplary damages of any character arising as a
144
+ result of this License or out of the use or inability to use the
145
+ Work (even if such Contributor has been advised of the possibility
146
+ of such damages).
147
+
148
+ 9. Accepting Warranty or Liability. While redistributing the Work or
149
+ Derivative Works thereof, You may choose to offer, and charge a fee
150
+ for, acceptance of support, warranty, indemnity, or other liability
151
+ obligations and/or rights consistent with this License. However, in
152
+ accepting such obligations, You may offer only obligations consistent
153
+ with this License and for which You can fully compensate for any
154
+ resulting liability.
155
+
156
+ END OF TERMS AND CONDITIONS
157
+
158
+ Copyright 2026 INNO LOTUS PTY LTD
159
+
160
+ Licensed under the Apache License, Version 2.0 (the "License");
161
+ you may not use this file except in compliance with the License.
162
+ You may obtain a copy of the License at
163
+
164
+ http://www.apache.org/licenses/LICENSE-2.0
165
+
166
+ Unless required by applicable law or agreed to in writing, software
167
+ distributed under the License is distributed on an "AS IS" BASIS,
168
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
169
+ implied. See the License for the specific language governing
170
+ permissions and limitations under the License.
@@ -0,0 +1,7 @@
1
+ Neural Protocol Suite (NPS)
2
+ Copyright 2026 INNO LOTUS PTY LTD
3
+
4
+ This product includes software developed under the LabAcacia open-source lab,
5
+ operated by INNO LOTUS PTY LTD (https://innolotus.com).
6
+
7
+ NCP (Neural Communication Protocol) v0.2 was developed by Ori Lynn / INNO LOTUS PTY LTD.
nps_sdk/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ # Copyright 2026 INNO LOTUS PTY LTD
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """NPS SDK — Python client library for the Neural Protocol Suite."""
5
+
6
+ from importlib.metadata import version, PackageNotFoundError
7
+
8
+ try:
9
+ __version__: str = version("nps-sdk")
10
+ except PackageNotFoundError:
11
+ __version__ = "0.1.0"
12
+
13
+ __all__ = ["__version__"]
@@ -0,0 +1,31 @@
1
+ # Copyright 2026 INNO LOTUS PTY LTD
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """NPS Core — frame header, codec, and anchor cache."""
5
+
6
+ from nps_sdk.core.frames import EncodingTier, FrameFlags, FrameType, FrameHeader
7
+ from nps_sdk.core.exceptions import (
8
+ NpsError,
9
+ NpsFrameError,
10
+ NpsCodecError,
11
+ NpsAnchorNotFoundError,
12
+ NpsAnchorPoisonError,
13
+ )
14
+ from nps_sdk.core.codec import Tier1JsonCodec, Tier2MsgPackCodec, NpsFrameCodec
15
+ from nps_sdk.core.cache import AnchorFrameCache
16
+
17
+ __all__ = [
18
+ "EncodingTier",
19
+ "FrameFlags",
20
+ "FrameType",
21
+ "FrameHeader",
22
+ "NpsError",
23
+ "NpsFrameError",
24
+ "NpsCodecError",
25
+ "NpsAnchorNotFoundError",
26
+ "NpsAnchorPoisonError",
27
+ "Tier1JsonCodec",
28
+ "Tier2MsgPackCodec",
29
+ "NpsFrameCodec",
30
+ "AnchorFrameCache",
31
+ ]
nps_sdk/core/cache.py ADDED
@@ -0,0 +1,131 @@
1
+ # Copyright 2026 INNO LOTUS PTY LTD
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """
5
+ AnchorFrameCache — in-process cache for AnchorFrame instances (NPS-1 §4.1).
6
+
7
+ Design notes:
8
+ - anchor_id is sha256:{64 hex chars} of the canonical (field-sorted) schema JSON.
9
+ - Idempotent set(): identical schemas produce the same key; no duplicate entries.
10
+ - Anchor poisoning protection: same anchor_id + different schema → NpsAnchorPoisonError.
11
+ - TTL is implemented via a simple timestamp-based expiry (no external dependency).
12
+ - Thread-safety: not required for single-threaded async use; add a threading.Lock
13
+ if used from multiple OS threads.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import json
20
+ import time
21
+ from typing import TYPE_CHECKING
22
+
23
+ from nps_sdk.core.exceptions import NpsAnchorNotFoundError, NpsAnchorPoisonError
24
+
25
+ if TYPE_CHECKING:
26
+ from nps_sdk.ncp.frames import AnchorFrame, FrameSchema
27
+
28
+
29
+ class AnchorFrameCache:
30
+ """
31
+ In-process cache for AnchorFrame instances, keyed by sha256 anchor_id.
32
+ """
33
+
34
+ def __init__(self) -> None:
35
+ # Stored as: anchor_id → (AnchorFrame, expires_at)
36
+ self._store: dict[str, tuple["AnchorFrame", float]] = {}
37
+
38
+ # ── Public API ────────────────────────────────────────────────────────────
39
+
40
+ def set(self, frame: "AnchorFrame") -> str:
41
+ """
42
+ Store *frame* and return its canonical anchor_id.
43
+
44
+ If an entry already exists for the same anchor_id, the schemas are compared.
45
+ A mismatch raises NpsAnchorPoisonError (NPS-1 §7.2).
46
+
47
+ Returns:
48
+ The canonical ``sha256:{64 hex chars}`` anchor_id.
49
+ """
50
+ anchor_id = (
51
+ frame.anchor_id
52
+ if frame.anchor_id.startswith("sha256:")
53
+ else self.compute_anchor_id(frame.schema)
54
+ )
55
+
56
+ if anchor_id in self._store:
57
+ existing_frame, expires_at = self._store[anchor_id]
58
+ if time.monotonic() < expires_at:
59
+ if not self._schemas_equal(existing_frame.schema, frame.schema):
60
+ raise NpsAnchorPoisonError(anchor_id)
61
+ # Same schema — idempotent; refresh TTL
62
+
63
+ expires_at = time.monotonic() + frame.ttl
64
+ self._store[anchor_id] = (frame, expires_at)
65
+ return anchor_id
66
+
67
+ def get(self, anchor_id: str) -> "AnchorFrame | None":
68
+ """Return the cached frame, or *None* if not present or expired."""
69
+ entry = self._store.get(anchor_id)
70
+ if entry is None:
71
+ return None
72
+ frame, expires_at = entry
73
+ if time.monotonic() > expires_at:
74
+ del self._store[anchor_id]
75
+ return None
76
+ return frame
77
+
78
+ def get_required(self, anchor_id: str) -> "AnchorFrame":
79
+ """Return the cached frame, or raise NpsAnchorNotFoundError."""
80
+ frame = self.get(anchor_id)
81
+ if frame is None:
82
+ raise NpsAnchorNotFoundError(anchor_id)
83
+ return frame
84
+
85
+ def invalidate(self, anchor_id: str) -> None:
86
+ """Remove an entry from the cache (no-op if not present)."""
87
+ self._store.pop(anchor_id, None)
88
+
89
+ def __len__(self) -> int:
90
+ self._evict_expired()
91
+ return len(self._store)
92
+
93
+ # ── Static helpers ────────────────────────────────────────────────────────
94
+
95
+ @staticmethod
96
+ def compute_anchor_id(schema: "FrameSchema") -> str:
97
+ """
98
+ Compute the deterministic ``sha256:{64 hex chars}`` anchor_id for *schema*.
99
+ Fields are sorted by name before hashing to ensure order-independence
100
+ (NPS-1 §4.1).
101
+ """
102
+ sorted_fields = sorted(
103
+ [
104
+ {k: v for k, v in f.items() if v is not None}
105
+ for f in [
106
+ {
107
+ "name": field.name,
108
+ "type": field.type,
109
+ "semantic": field.semantic,
110
+ "nullable": field.nullable,
111
+ }
112
+ for field in schema.fields
113
+ ]
114
+ ],
115
+ key=lambda d: d["name"],
116
+ )
117
+ canonical = json.dumps(sorted_fields, separators=(",", ":"), sort_keys=True)
118
+ digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
119
+ return f"sha256:{digest}"
120
+
121
+ # ── Private ───────────────────────────────────────────────────────────────
122
+
123
+ def _evict_expired(self) -> None:
124
+ now = time.monotonic()
125
+ expired = [k for k, (_, exp) in self._store.items() if now > exp]
126
+ for k in expired:
127
+ del self._store[k]
128
+
129
+ @staticmethod
130
+ def _schemas_equal(a: "FrameSchema", b: "FrameSchema") -> bool:
131
+ return AnchorFrameCache.compute_anchor_id(a) == AnchorFrameCache.compute_anchor_id(b)